Variables in JavaScript

Like any programming language, variables in JavaScript store values.

Use the let keyword to create a JavaScript variable.

let studentName = “John”;
console.log(studentName);

Type the above piece of code in Plunker editor https://plnkr.co/edit/?p=preview. Press F12 IN Chrome to see the output in console.

Its a good practice to create variables in JS using camel case notation.

Use comma to create multiple variables.

let studentName = “John”,
studentId = “111”;
console.log(studentName, studentId);

If you are using apostrophe, then use \ ( back slash for it to show)

let yourName = ‘What\’s your name?’;
console.log(yourName);

Numeric Variables in JavaScript

let price = 5.00;
console.log(price);

The output is : 5

Arithmetic operators for numeric variables

JavaScript uses the common arithmetic numeric variables.

+ for addition , – for subtraction , * for multiplication, / for division,% for modulus.

Adding Numeric variable with String

If you try to add a numeric variable with a string, it treats the number as a string.

let myId = 1,
myName = “Amit”;
console.log(myId + myName);

The output is: 1Amit

Some Interesting behavior of JS with numbers

let abc = 2.1 + 2.3;
console.log(abc);

The output is: 4.399999999999999

let abc = 2 /  0;
console.log(abc);

The output is: Infinity

let abc = -2 /  0;
console.log(abc);

The output is: -Infinity

let abc = 0/  0;
console.log(abc);

The output is: NaN

You can use the typeof Keyword to know the type of a variable

let abc = 0/  0;
console.log(typeof(abc));

The output is: Number

JavaScript Boolean variables

Boolean can value as ‘true’  or ‘false’.

let abc = true;
console.log(typeof(abc));

The output is: boolean

Undefined and Null in JavaScript

undefined : JavaScript will initialize variables to undefined

null: developers cannot initialize a variable to undefined. They should assign a variable to null.

let abc;
console.log(abc);

The output is: undefined

let abc;
abc = null;
console.log(abc);

The output is: null

efined

let abc;
abc = null;
console.log(abc, typeof(abc));

The output is: null  “object”

Concatenate Strings in JavaScript

let firstName = “John”,
lastName = “Doe”;
console.log(firstName + lastName);

The output is: JohnDoe