Categories
JavaScript Basics

JavaScript Cheat Sheet — Operators and Dates

JavaScript is one of the most popular programming languages for web programming.

In this article, we’ll look at the basic syntax of modern JavaScript.

Operators

We can do arithmetic with JavaScript.

We add with + and subtract with - :

let a = b + c - d;

We multiply with * and divide with / :

let a = b * (c / d);

And we get the remainder of one number divided by another with / :

let x = 100 % 48;

We increment with ++ :

a++;

And we decrement with -- :

b--;

Typeof

We can get type of primitive values and objects with typeof :

typeof a

It’s mostly useful for primitive values since it returns 'object' for all objects.

Assignment

We assign one value to a variable with = :

let x = 10

The right expression is assigned to the variable on the left.

a +=b is short for a = a + b . We can also replace + with - , * and / .

Comparison

We compare equality with === :

a === b

We check for inequality with !== :

a !== b

We check if a is greater than b with:

a > b

And we check if a is less than b with:

a < b

We can check for less than or equal with:

a <= b

And we check for greater than or equal with:

a >= b

Logical AND is && :

a && b

And logical OR is || :

a || b

Dates

We can create date objects with the Date constructor:

let d = new Date("2017-06-23");

If we omit the month and day, then it’s set to January 1:

let d = new Date("2017");

We can add the hour, minutes, and seconds with:

let d = new Date("2017-06-23T12:00:00-09:45");

Human readable date also works:

let d1 = new Date("June 23 2017");
let d2 = new Date("Jun 23 2017 07:45:00 GMT+0100 (Tokyo Time)");

A date object comes with methods to let us get various values from it.

We call them by writing:

let d = new Date();
let a = d.getDay();

getDay() gets the day of the week

getDate() gets the day of the month as a number.

getFullYear() gets the 4 digit year.

getHours() gets the hours.

getMilliseconds() gets the milliseconds.

getMinutes() gets the minutes.

getMonth() gets the month.

getSeconds() gets the seconds.

getTime() gets the milliseconds since 1970, January 1.

We can also set values with some setter methods.

To call them, we write:

let d = new Date();
d.setDate(d.getDate() + 7);

setDay() sets the day of the week

setDate() sets the day of the month as a number.

setFullYear() sets the 4 digit year.

setHours() sets the hours.

setMilliseconds() sets the milliseconds.

setMinutes() sets the minutes.

setMonth() sets the month.

setSeconds() sets the seconds.

setTime() sets the timestamp.

Conclusion

JavaScript comes with various operators and the Date constructor to let us create, get, and set dates.

Categories
JavaScript Basics

JavaScript Cheat Sheet — Spread, Variables, and Conditionals

JavaScript is one of the most popular programming languages for web programming.

In this article, we’ll look at the basic syntax of modern JavaScript.

Spread Operator

We can use the spread operator to add properties from other objects to an object.

For instance, we can write:

const a = {
 frstName: "james",
 lastName: "smith",
}
const b = {
 ...a,
 lastName: "White",
 canSing: true,
}

Then b is:

{
  "frstName": "james",
  "lastName": "White",
  "canSing": true
}

Destructuring Nested Objects

We can destructure nested objects into variables.

For instance, we write:

const bob = {
  name: "bob jones",
  age: 29,
  address: {
    country: "Westeros",
    state: "Crownlands",
    pinCode: "500014",
  },
};
const {
  address: {
    state,
    pinCode
  },
  name
} = bob;

Then state is 'Crownlands' and pinCode is '500014' .

Exponent Operator

We can use the exponent operator to do exponentiation.

So we can write: 2 ** 8 and get 256.

Promises with finally

We can call finally to run code regardless of the result of a promise.

For example, we write:

Promise.resolve(1)
  .then((result) => {})
  .catch((error) => {})
  .finally(() => {})

if-else

We can use a if-else to write code that runs conditionally.

For instance, we can write:

if ((age >= 15) && (age < 19)) {
  status = "Eligible.";
} else {
  status = "Not eligible.";
}

If age is between 15 and 19 then the first block runs.

Otherwise, the 2nd block runs.

Switch Statement

We can use the switch statement to check for more than one case and run code if the value matches.

For instance, we write:

switch (new Date().getDay()) {
  case 6:
    text = "Saturday";
    break;
  case 0:
    text = "Sunday";
    break;
  default:
    text = "";
}

If getDay returns 6 then text is 'Saturday' .

If it returns 0, then text is 'Sunday' .

Otherwise, text is an empty string.

Assign Variables

We can assign variables with let :

let x

x is uninitialized.

We can initialize it:

let y = 1

We can assign it a string:

let a = 'hi'

We can assign it an array:

let b = [1,2,3]

And we can assign it a boolean:

let c = false;

And regex:

let d = /()/

Or assign it a function:

let e = function(){};

And we can create a constant:

const PI = 3.14;

We can assign multiple variables in a line:

let a = 1, b = 2, c = a + b;

Strict Mode

We can add 'use strict' to our code to make us write better JavaScript code.

For instance, we can’t write code like:

a = 1

since strict mode will stop global variables from being created.

Values

JavaScript has some values like booleans:

false, true

Numbers:

1.2, 0n001, 0xF6, NaN

Strings:

'foo', 'bar'

And reserved words for special values:

null, undefined, Infinity

Conclusion

JavaScript comes with various constructs to help us create programs.

Categories
JavaScript Basics

JavaScript Cheat Sheet — Basic ES6 Syntax and Methods

JavaScript is one of the most popular programming languages for web programming.

In this article, we’ll look at the basic syntax of modern JavaScript.

Arrow function

const sum = (a, b) => a + b

sum(1, 2) returns 3.

Default parameters

function print(a = 5) {
  console.log(a)
}

print() logs 5.

let scope

We can use let to declare variables:

let a = 3
if (true) {
  let a = 10
  console.log(a)
}

console.log should log 10.

const

const variables can only be assigned once when we initialize it:

const a = 11

We’ll get an error if we try to assign a again.

Multiline String

We can create multine string with backticks (`):

console.log(`
  This is a
  multiline string
`)

Template Strings

We can interpolate expressions with ${} :

const name = 'james'
const message = `Hello ${name}`

Then message is 'Hello james'

String includes()

We can use the includes method to check if a string has the given substring.

So

'apple'.includes('pl')

returns true .

String startsWith()

The startsWith method lets us check if a string starts with a given substring:

'apple'.startsWith('ap')

String repeat()

We can use the repeat method to repeat a string:

'ab'.repeat(3)

returns ‘ababab’ .

Destructuring Array

We can use the destructuring syntax to assign array entries to variables.

For instance, we write:

let [a, b] = [3, 10];

Then a is 3 and b is 10.

Destructuring Object

We can assign object properties to variables with the destructuring syntax.

For example, if we have:

let obj = {
  a: 15,
  b: 20
};
let {
  a,
  b
} = obj;

Then a is 15 and b is 20.

Object Property Assignement

We can assign properties to objects with the object property assignment syntax.

For instance, we write:

const a = 2
const b = 5
const obj = {
  a,
  b
}

Then obj is:

{a: 2, b: 5}

Object Function Assignment

We can add methods to an object with the shorthand syntax:

const obj = {
  a: 'foo',
  b() {
    console.log('b')
  }
}

Then we can call obj.b() to log 'b' .

Spread Operator

The spread operator lets us combine arrays into one.

For instance, we write:

const a = [1, 2]
const b = [3, 4]
const c = [...a, ...b]

And c is [1, 2, 3, 4] .

Object.assign()

The Object.assign method lets us combine multiple objects into one.

For instance, we write:

const obj1 = {
  a: 1
}
const obj2 = {
  b: 2
}
const obj3 = Object.assign({}, obj1, obj2)

Then obj3 is { a: 1, b: 2 } .

Object.entries()

We can get the object’s key-value pairs into an array with the Object.entries() method.

For instance, we write:

const obj = {
  frstName: 'james',
  lastName: 'smith',
  age: 22,
  country: 'uk',
};
const entries = Object.entries(obj);

Then Object.entries returns:

[
  [
    "frstName",
    "james"
  ],
  [
    "lastName",
    "smith"
  ],
  [
    "age",
    22
  ],
  [
    "country",
    "uk"
  ]
]

Conclusion

JavaScript comes with useful syntax and methods in the standard library we can use.

Categories
JavaScript Basics

Using Strings in JavaScript

Defining Strings

It can take a few forms, like in the following code:

'string'
`string`
'日本語'

These are called string literals. The first string is a normal string. The second one is a template string literal. They are primitive values and have the type ‘string’. We can also define strings with the String function, like in the following code:

String(1)

The code above would return '1' since we convert the number 1 into a string. This can be done with all primitive values, like in the following examples:

String(true)
String('string')
String(undefined)
String(null)
String(Symbol('a'))

If we log the code above line by line, we would get:

true
string
undefined
null
Symbol(a)

However, the String method doesn’t work very well with objects like in the following code:

const str = String({
  a: 1
});
console.log(str);

The code above will get us [object Object]. However, if an object has a toString() function, then we would get something useful when using the String function to convert it to a string. For example, if we have:

const str = String({
  a: 1,
  toString(){
   return JSON.stringify(this)
  }
});
console.log(str);

console.log(String([1, 2, 3]))
console.log(String(new Date()))

Then we get:

{"a":1}
1,2,3
Sun Oct 27 2019 10:30:54 GMT-0700 (Pacific Daylight Time)

As we can see, if we added a toString() method to an object then we can get a string representation of it with the String function. This is the same with arrays and the Date object, which both have the toString() method built-in.

If we have:

console.log([1, 2, 3].toString())
console.log(new Date().toString())

Then we get the same output as in the previous example.

Escape Characters

In addition to regular printable characters, strings can also have special characters that can be escaped. The following are the escape characters that can be added into strings:

  • XXX (XXX = 1 – 3 octal digits; range of 0 – 377) — ISO-8859-1 character / Unicode code point between U+0000 and U+00FF
  • ' — single-quote
  • " — double quote
  • “ —backslash
  • n —new line
  • r — carriage return
  • v — vertical tab
  • t — tab
  • b — backspace
  • f — form feed
  • uXXXX (XXXX = 4 hex digits; range of 0x0000 – 0xFFFF)UTF-16 code unit / Unicode code point between U+0000 and U+FFFF
  • u{X}u{XXXXXX} (X…XXXXXX = 1 – 6 hex digits; range of 0x0 – 0x10FFFF) UTF-32 code unit / Unicode code point between U+0000 and U+10FFFF
  • xXX (XX = 2 hex digits; range of 0x00 – 0xFF)ISO-8859-1 character / Unicode code point between U+0000 and U+00FF

Long strings can be concatenated together if they need to wrap into the next line with the + operator. For example, if we have a long string like the one below, we can write:

`let longString = "`Lorem ipsum dolor sit amet, consectetur `" +
                 "`adipiscing elit. Nulla nec facilisis libero, `" +
                 "`nec pulvinar est.`";`

More convenient ways to wrap long strings are using a slash character or use a string template literal. With the slash character, we can rewrite the string above with:

`let longString = "`Lorem ipsum dolor sit amet, consectetur   adipiscing elit. Nulla nec facilisis libero, `` nec pulvinar est.`";`

To write it with a template string, we can write:

let longString = `Lorem ipsum dolor sit amet, consectetur adipiscingelit. Nulla nec facilisis libero, nec pulvinar est.`;

Since spacing is preserved with template strings, we do not want to add extra spacing. Instead, we want to let it automatically wrap into the next line.

String Operations

We can access a character of a string by using the charAt method or using the bracket notation like accessing an entry in an array. To use the charAt method, we can write:

'dog'.charAt(1)

This would return ‘o’. Equivalently, we can use the bracket notation to get the same character as in the following code:

'dog'[1]

Which should get the same output when logged. We can’t delete or reassign a character with this notation since it’s not writable and its property descriptors can’t change, and it can’t be deleted.

To compare strings, we can use the normal comparison operators that we use like with anything else. For example, we can write:

console.log('a' < 'b');
console.log('a' > 'b');
console.log('a' == 'b');
console.log('a' === 'b');

The code above would get us:

true
false
false
false

The order is determined by the Unicode character code’s order in the list of characters or the collation specification depending on the locale. This means that the sort order may be different for different languages. String comparisons are case sensitive. For case insensitive comparisons, we have to convert them to the same case. For the best result, we should convert all the strings to uppercase since some Unicode characters don’t convert properly when converted to lowercase. For example, if we want to do case insensitive equality check then we can write:

console.log('abc'.toUpperCase() === 'Abc'.toUpperCase());

The code above would show true in the console.log .

In JavaScript, there’s also a string object, in addition to string literals. Strings can be defined with the String constructor by using the new String() constructor. With the String constructor, we get that the string will be type object even though everything else is the same. A string literal will have type string. For example, if we have the following code:

const sPrim = 'foo';
const sObj = new String(sPrim);
console.log(typeof sPrim);
console.log(typeof sObj);

The first console.log would show ‘string’ and the second one would show ‘object’. With the valueOf method, we can convert a string object into a primitive string. For example, we can write:

const sPrim = 'foo';
const sObj = new String(sPrim);
console.log(typeof sPrim);
console.log(typeof sObj.valueOf());

Then we get that both console.log statements would show ‘string’.

Basic Methods

To take full advantage of strings, we have to be able to manipulate them. Fortunately, strings have plenty of available methods to make manipulating them easy.

String.substr()

JavaScript strings have a substr function to get the substring of a string.

It takes a starting index as the first argument and a number of characters from the start index as the second argument.

It can be used like this:

const str = "Hello Bob";
const res = str.substr(1, 4); // ello

String.substring()

JavaScript strings also have a substring function that takes the start and end index as two arguments and returns a string with the ones between the start and end indices.

The start index is included but the end index is excluded.

Example:

const str = "Hello Bob";
const res = str.substring(1, 3); // el

String.toLocaleLowerCase()

Converts a string to lowercase, according to the locale of your browser. The new string is returned, instead of modifying the original string.

For example:

const str = "Hello Bob!";
const res = str.toLocaleLowerCase(); // hello bob!

String.toLocaleUpperCase()

Converts a string to uppercase, according to the locale of your browser. The new string is returned, instead of modifying the original string.

For example:

const str = "Hello Bob!";
const res = str.toLocaleUpperCase(); // 'HELLO BOB!'

String.toLowerCase()

Converts a string to lowercase. The new string is returned, instead of modifying the original string.

For example:

const str = "Hello Bob!";
const res = str.toLocaleLowerCase(); // 'hello bob!'

String.toUpperCase()

Converts a string to uppercase. The new string is returned, instead of modifying the original string.

For example:

const str = "Hello Bob!";
const res = str.toLocaleUpperCase(); // 'HELLO BOB!'

String.trim()

Remove starting and ending white space from a string.

For example:

const str = "         Hello Bob!     ";
const res = str.trim(); // 'Hello Bob!'

String.repeat()

To use the repeat function, you pass in the number of times you want to repeat the string as an argument. It returns a new string.

For example:

const hello = "hello";
const hello5 = A.repeat(5);
console.log(hello5); // "hellohellohellohellohello"

String.startsWith()

startsWith checks if a string starts with the substring you pass in.

For example:

const str = "Hello world.";
const hasHello = str.startsWith("Hello"); // trueconst str2 = "Hello world.";
const hasHello2 = str.startsWith("abc"); // false

String.endsWith()

endsWith checks if a string ends with the substring you pass in.

For example:

const str = "Hello world.";
const hasHello = str.endsWith("world."); // trueconst str2 = "Hello world.";
const hasHello2 = str.endsWith("abc"); // false

String.indexOf()

indexOf finds the index of the first occurrence of the substring. Returns -1 if not found.

For example:

const str = "Hello Hello.";
const hasHello = str.indexOf("Hello"); // 0
const hasHello2 = str.indexOf("abc"); // -1

String.lastIndexOf()

lastIndexOf finds the index of the last occurrence of the substring. Returns -1 if not found.

For example:

const str = "Hello Hello.";
const hasHello = str.lastIndexOf("Hello"); // 6
const hasHello2 = str.lastIndexOf("abc"); // -1

String.charAt()

charAt returns the character located at the index of the string.

For example:

const str = "Hello";
const res = str.charAt(0); // 'H'

String.search()

search gets the position of the substring passed into the function. It returns -1 if the substring is not found in the string.

Example:

const str = "Hello";
const res = str.search('H'); // 0

String.includes

includes checks if the passed-in substring is in the string. Returns true if it is in the string, false otherwise.

const str = "Hello";
const hasH = str.includes('H'); // true
const hasW = str.includes('W'); // false

String.replace()

The replace() function is useful for replacing parts of strings with another. It returns a new string with the string after the substring is replaced.

Example:

const str = "Hello Bob";
const res = str.replace("Bob", "James"); // 'Hello James'

replace() can also be used to replace all occurrences of a substring using the Regex g global property.

For example:

const str = "There are 2 chickens in fridge. I will eat chickens today.";
const res = str.replace(/chickens/g, "ducks"); // "There are 2 ducks in fridge. I will eat ducks today."

If the first argument is a regular expression that searches globally, it will replace all occurrences of the substring.

Strings are an important global object in JavaScript. It represents a sequence of characters. It can be used by various operators like comparison operators and it has methods that can manipulate them. Other important methods include searching of strings with the includes method and the indexOf method. They also have a trim() method to trim strings.

Categories
JavaScript Basics

Check JavaScript Variable Data Types with the Typeof Operator

The typeof operator in JavaScript is useful for checking primitive types.

JavaScript is a loosely typed or a dynamically typed language. This means that a variable that’s declare with one type can be converted to another type without explicitly converting the data to another type. Variables can also contain any type at any time depending on what’s assigned. JavaScript has multiple data types. There are 7 primitive data types and an object type. The 7 primitive types are boolean, null, undefined, number, BigInt, string and symbol. Since there are different data types and they a variable or an object’s properties’ types can change anything, we need a way to check for the type of data of an variable or an object’s property.

To check for the type of an object’s property or a variable, we use the typeof operator of an object. It lets us get the type name of an object or its properties with as a string. We can use it as allows:

typeof x

Where x is a variable’s name. This is the only operand of the typeof operator. The check the type of an object’s property, we can write:

typeof x.prop

With the code above we can conveniently get the type of the prop property of x . The typeof operator returns a string containing the name of the type of the operand. It can return the following types names as a string:

  • Objects with the undefined type will return 'undefined'
  • Objects with the null type will return 'object'
  • Objects with the boolean type will return 'boolean'
  • Objects with the number type will return 'number'
  • Objects with the BigInt type will return 'bigint'
  • Objects with the String type will return 'string'
  • Objects with the Symbol type will return 'symbol'
  • Objects with the Function type will return 'function'
  • Any other types of object will return 'object'

We can use the typeof operator like in the following examples:

Numbers

The following operands will return 'number' if the typeof operator is applied to it. Therefore, all of the expressions when logged will output true .

typeof 1 === 'number';
typeof 3.1 === 'number';
typeof(2) === 'number';
typeof Math.LN10 === 'number';
typeof Infinity === 'number';
typeof NaN === 'number';
typeof Number('2') === 'number';
typeof Number('shoe') === 'number';

The number type is a double precision 64 bit number that can have values between negative 2 to the 53rd power minus one to 2 to the 53rd power minus one. There’s no specific type for integers. All numbers are floating point numbers. There’re also 3 symbolic values: Infinity , -Infinity and NaN . These are all within the range or are Infinity , -Infinity or NaN so they all have the type of 'number' . Number(‘shoe’) returns NaN and since NaN is of type number, typeof Number(‘shoe’) is number.

Strings

The following operands will return 'string' if the typeof operator is applied to it. Therefore, all of the expressions when logged will output true .

typeof '' === 'string';
typeof 'abc' === 'string';
typeof `template string` === 'string';
typeof '2' === 'string';
typeof (typeof 2) === 'string';
typeof String(1) === 'string';

Strings are used to represent textual data. Each element of the string has its own position in the string. It’s zero indexed, so the position of the first character of a string is 0. The length property of the string has the total number of characters of the string.

JavaScript strings are immutable. We cannot modify a string that has been created, but we can still create a new string that contains the originally defined string. We can extract substrings from a string with the substr() function and use the concat() function to concatenate 2 strings.

In JavaScript, anything surrounded by single quotes, double quotes, or backticks are strings. Single and double quote surround normal strings, and backticks surround template strings. The String function converts anything to a string, so String(1) returns '1' , so it’s of type string. The typeof operator returns a string, so if we are applying the typeof operator to the result returned by typeof , then that should be a string.

Booleans

The following operands will return 'boolean' if the typeof operator is applied to it. Therefore, all of the expressions when logged will output true .

typeof true === 'boolean';
typeof false === 'boolean';
typeof Boolean(2) === 'boolean';
typeof !!(2) === 'boolean';

The Boolean function and the double not operator (!! ) will both convert truthy values to true and falsy values to false . Falsy values in JavaScript includes 0, empty string, null , undefined , and false . So if they are passed in as as arguments to the Boolean function then they are converted to false . Everything else is truthy, so they’re converted to true with the Boolean function or the double not operator.

Symbols

The following operands will return 'symbol' if the typeof operator is applied to it. Therefore, all of the expressions when logged will output true .

typeof Symbol() === 'symbol'
typeof Symbol('foo') === 'symbol'
typeof Symbol.iterator === 'symbol'

Symbols are new to ES2015. It is unique and immutable identifier. Once you created it, it cannot be copied. Every time you create a new Symbol it is a unique one. It’s mainly used for unique identifiers in an object. It’s a Symbol’s only purpose.

The Symbol function creates a new symbol, so anything returned by it is of type symbol. Symbol.iterator is a special symbol, so that’s also of type symbol.

Undefined

The following operands will return 'undefined' if the typeof operator is applied to it. Therefore, all of the expressions when logged will output true .

typeof undefined === 'undefined';
typeof declaredVariableWithoutValueAssigned === 'undefined';
typeof undeclaredVariable === 'undefined';

A variable that has not been assigned a value has type undefined. If you do not assign a value to a declared variable or try to reference an undeclared variable, then you would get type undefined if you apply the typeof operator to them. Likewise, if you have never declared the property of an object or have declared the property haven’t assigned a value to it, those properties will also have the undefined type.

Objects

The following operands will return 'object' if the typeof operator is applied to it. Therefore, all of the expressions when logged will output true .

typeof {a: 1} === 'object';
typeof [1, 2, 4] === 'object';
typeof null === 'object';
typeof new Date() === 'object';
typeof /regex/ === 'object';

Object is a reference data type, which means it can be referenced by an identifier which points to location of the location of the object in memory. In memory, the object’s value is stored, and with the identifier, we can access the value. Object has properties, which are key-value pairs with the values being able to contain the data with primitive types or other objects, which means we can use object to build complex data structures.

In addition to data with key-value pairs having the type object, the null type also returns object when the typeof operator is operated on it. Arrays and other iterable objects also return object as the type when we apply the operator to it to get the type, since these kinds of data are also objects in JavaScript. To check if an object is an array, we can use the Array.isArray function to determine if an object is an array.

Functions

The following operands will return 'function' if the typeof operator is applied to it. Therefore, all of the expressions when logged will output true .

typeof function() {} === 'function';
typeof class C {} === 'function';
typeof Math.sin === 'function';

Functions are objects in JavaScript. Any kinds of functions, like arrow functions, functions declares with the function keyword, and classes are of type function. Note that classes in JavaScript is just syntactic sugar for functions that we can create new objects with. Therefore, classes are still of type function.

BigInts

The following operands will return 'bigint' if the typeof operator is applied to it. Therefore, all of the expressions when logged will output true .

typeof 42n === 'bigint';

In JavaScript, there is the BigInt type to store numbers that are beyond safe integer range. A BigInt number can be created by adding an n character to the end of a number. With BigInt, we can make calculations that have results beyond the safe range of normal numbers. So any number that ends with an n will be of type bigint .

New Operator

The new Operator will always return an object to whatever it’s applied to, so the following will always have type object. The following operands will return 'object' if the typeof operator is applied to it. Therefore, all of the expressions when logged will output true .

typeof new Boolean(true) === 'object';
typeof new Number(1) === 'object';
typeof new String('abc') === 'object';
`typeof new String(null)` === 'object';`typeof new Number(undefined)` === 'object';

Notice that no matter what we have, we get type object if the new keyword is used to create the object. It doesn’t matter whether it’s boolean, number, string, or whatever you pass in, Therefore, when we don’t need to use the new keyword to create the object, then don’t do it. To convert things to boolean, we use the Boolean function, to convert things to numbers we use the Number function, and to convert things to a string, we use the String function.

Null Type

null objects are of type object because they were represented by type tag 0. The null pointer for JavaScript is 0x00 like in most platforms. Therefore, null has type tag 0, so object has object as the type returned by typeof .

Determining Types of Expressions

We can use the typeof operator to determine the type of entities returned by expressions. We parentheses to determine the type of the result combined together in expressions. For example, if we want to get the type of 1 + ‘1’ , then we need to write:

typeof (1 + '1');

If we write the code above, we get string as the type, which is the correct type of the result of the expression. If we don’t put parentheses around the expression, then we only get the type of the first part of the expression, which is number concatenated with '1' .

Errors

Using the typeof operator before a variable declared with let or const will result in a ReferenceError being thrown, since it’s referencing a variable that’s not declared yet. Previous using the typeof operator on undeclared variables will return the type 'undefined’. The typeof operator never generated an error before ES2015.

For example, if we have:

typeof letVariable;
typeof constant;
typeof c;

let letVariable;
const constant = 'constant';
class c{};

The first 3 lines will throw a ReferenceError when they’re run.

The typeof operator is useful for checking types of primitive types and objects. For primitive types, it will return the type of the object, except for null type, which will return object as the type. Objects, including arrays and other iterable objects, will always return object as the type. With variables declared with let or const keywords and classes, we have to declare them before using the typeof operator on them.