Let’s start with the differences between string and numbers in JS.
To create a string — just wrap any sequence of characters in quotes.
Quotes can be single, double or backtick.
let hello = 'Hello, World!'; let name = "John"; let s = `some string`;
In all three cases, we’re saving string values into the variables
let name = 'Jack'; let surname = 'Jones'; let fullName = name + surname;
Let’s try to log the value of the variable
Here’s the output:
To add a space between
Jones, we should update our code a bit.
Let’s start with the same string
Jack, add a string that consists of a single space character to it and follow up with a string
Jones are stored in the variables
surname, we can use them.
let fullName = name + ' ' + surname; console.log(fullName);
The output will change, and you’ll notice an extra space between the name and surname.
Number can be both integers and floating point.
let a = 1; let b = 0.5; let c = -15.25; let year = 2021;
In the code snippet above we’ve created 4 variables
year and saved 4 values
2021 in them.
Take a note that this time we haven’t used quotes.
You can print out numbers to the console the same way as you’ve printed strings.
Two messages will appear:
The differences between numbers and strings become evident when we try to save them.
let x = 2; let y = 3; let sum = x + y; console.log(sum);
Once you run this program you’ll see the number
5 in the console.
Let’s check what happens when we wrap
y in quotes:
let x = '2'; let y = '3'; let sum = x + y; console.log(sum);
In this case the string
We can create a variable, save a number in it and then overwrite it with a string.
let x = 1; let y = 2; console.log(x + y); y = 'hello'; console.log(x + y);
We’ve saved the number
2 into the variables
y. After this, we added them and printed the result to the screen. No surprises here and the output was
Right after the first
console.log we’ve overwritten the value of
y with the string
y in a proper mathematical fashion. Number
1 is “glued” to the string
hello and we end up with
The developer had a task to save the values
3 into the variables
y and print out their sum to the screen. Looks like he made a mistake and used strings instead of numbers.
let x = '2'; let y = '3'; console.log(x + y);
Fix the code by changing strings to numbers.
In this task the variables were created, but they were initialized with empty strings.
let greeting = ''; let name = ''; console.log(greeting + ' ' + name);
Save the strings
Hero into the variables
2 + 2 = 4 should appear on the screen, but we got an error instead.
const result = 4; console.log('2 + 2 = ' + x);
You should fix the bug.
Let’s start with the blank page. Print out 3 numbers to the screen —
Each number should appear on a separate string.