The Tricky JavaScript

2021 Preparing for Front End Developer Interview (JS part 1)

Xinyi Zhao
8 min readMar 13, 2021

Fundamentals

“use strict” directive

  • Must be put at the top of a script file.
  • Goal: To explicitly enable modern code mode(ES5, ES6).
  • If the js file is full of import modules and classes, then no need to add “use strict” , it gets added automatically.

Data Type

  • JS is a dynamically typed language.
let message = “hello”;
message = 123456; // no error
  • The number type represents both integer and floating-point numbers.
let n = 123;
n = 12.345; // no error

the number type cannot represent integer values larger than (2^53 — 1) (that’s 9007199254740991), or less than -(2^53 — 1) for negatives.

In that case, we can use BigInt type to represent integers of arbitrary length. A BigInt value is created by appending n to the end of an integer (Right now, BigInt is supported in Firefox/Chrome/Edge/Safari, but not in IE).

// the "n" at the end means it's a BigInt
const bigInt = 1234567890123456789012345678901234567890n;

Normally, one uses null to assign an “empty” or “unknown” value to a variable, while undefined is reserved as a default initial value for unassigned things.

  • The typeof keyword allows us to see which type is stored in a variable.

typeof can be used as an operator, typeof “foo”or as a function typeof(true) .Two forms: typeof x or typeof(x).

Returns a string with the name of the type, like "string".

For null returns "object" – this is an error in the language, it’s not actually an object.

typeof undefined // "undefined"  
typeof 0 // "number"
typeof 10n // "bigint"
typeof Symbol("id") // "symbol"
typeof Math // "object"
// officially recognized error in typeof behavior, coming from the early days of JavaScript and kept for compatibility
typeof null // "object"
typeof alert // "function"

Interaction(alert, prompt, confirm)

  • alert function.
  • prompt function: The function prompt accepts two arguments:
result = prompt(title, [default]); // [] means the param is optional

It shows a modal window with a text message, an input field for the visitor, and the buttons OK/Cancel.

titleThe text to show the visitor.defaultAn optional second parameter, the initial value for the input field.

The visitor can type something in the prompt input field and press OK. Then we get that text in the result. Or they can cancel the input by pressing Cancel or hitting the Esc key, then we get null as the result.

The call to prompt returns the text from the input field or null if the input was canceled.

let age = prompt('How old are you?', 100);alert(`You are ${age} years old!`); // You are 100 years old!
  • confirm function:
let isBoss = confirm("Are you the boss?");  
alert( isBoss ); // true if OK is pressed

Type Conversion

  • Numeric conversion

Numeric conversion happens in mathematical functions and expressions automatically.

For example, when the division / is applied to non-numbers:

alert( "6" / "2" ); // 3, strings are converted to numbers

Numeric conversion rules:

undefined — — > NaN NOT 0!!!null — — > 0true or false — — > 1 or 0string — — > whitespaces from the start and end are removed, If the remaining string is empty, the result is 0. Otherwise, the number is “read” from the string. An error gives NaN.alert( Number("   123   ") ); // 123
alert( Number("123z") ); // NaN (error reading a number at "z") alert( Number(true) ); // 1
alert( Number(false) ); // 0

Boolean Conversion rules:

0, null, undefined, NaN, "" — — — -> falseany other value — — —> trueNote a non-empty string is always true.alert( Boolean("0") ); // true
alert( Boolean(" ") ); // spaces, also true (any non-empty string is true)

Operators

  • Exponentiation operator

The exponentiation operator a ** b multiplies a by itself b times. Mathematically, the exponentiation is defined for non-integer numbers as well. For example, a square root is an exponentiation by 1/2:

alert( 2 ** 4 ); // 16 (2 * 2 * 2 * 2, 4 times)
alert( 8 ** (1/3) ); // 2 (power of 1/3 is the same as a cubic root)
  • String Concatenation with binary +

Note that if any of the operands is a string, then the other one is converted to a string too. It doesn’t matter whether the first operand is a string or the second one. Operators work one after another.

alert( '1' + 2 ); // "12"
alert( 2 + '1' ); // "21"
alert(2 + 2 + '1' ); // "41" and not "221"
alert('1' + 2 + 2); // "122" and not "14"

The binary + is the only operator that supports strings in such a way. Other arithmetic operators work only with numbers and always convert their operands to numbers.

alert( 6 - '2' ); // 4, converts '2' to a number 
alert( '6' / '2' ); // 3, converts both operands to numbers
  • Numeric Conversion with unary +

The unary plus operator + applied to a single value, doesn’t do anything to numbers. But if the operand is not a number, the unary plus converts it into a number.

// No effect on numbers 
let x = 1;
alert( +x ); // 1
let y = -2;
alert( +y ); // -2
// Converts non-numbers
alert( +true ); // 1
alert( +"" ); // 0

It actually does the same thing as Number(someValue)but is shorter.

The need to convert strings to numbers arises very often. For example, if we are getting values from HTML form fields, they are usually strings. What if we want to sum them?

The binary plus would add them as strings:

let apples = "2";
let oranges = "3";
alert( apples + oranges ); // "23", the binary plus concatenates strings

If we want to treat them as numbers, we need to convert and then sum them:

let apples = "2";
let oranges = "3";
// both values converted to numbers before the binary plus
alert( +apples + +oranges ); // 5
// the longer variant
// alert( Number(apples) + Number(oranges) ); // 5

unary pluses are applied first, they convert strings to numbers, and then the binary plus sums them up.

  • Operator Precedence
Operator Precedence
  • Increment/decrement ++/--

It can only be applied to variables. Trying to use it on a value like 5++ will give an error.

The operators ++/-- can be used inside expressions as well. Their precedence is higher than most other arithmetical operations.

let counter = 1; 
alert( 2 * ++counter ); // 4
  • Comma

Each of them is evaluated but only the result of the last one is returned.

let a = (1 + 2, 3 + 4);
alert( a ); // 7 (the result of 3 + 4)

Here, the first expression 1 + 2 is evaluated and its result is thrown away. Then, 3 + 4 is evaluated and returned as the result.

Comma has very low precedence, lower than =, so parentheses are important in the example above.

Without them: a = 1 + 2, 3 + 4 evaluates + first, summing the numbers into a = 3, 7, then the assignment operator = assigns a = 3, and the rest is ignored. It’s like (a = 1 + 2), 3 + 4.

Comparisons

  • String comparison

To see whether a string is greater than another, JavaScript uses the so-called “dictionary” or “lexicographical” order. In other words, strings are compared letter-by-letter.

alert( 'Z' > 'A' ); // true
alert( 'Glow' > 'Glee' ); // true
alert( 'Bee' > 'Be' ); // true
  • Comparison of different types

When comparing values of different types, JavaScript converts the values to numbers.

alert( '2' > 1 ); // true, string '2' becomes a number 2 
alert( '01' == 1 ); // true, string '01' becomes a number 1

It is possible that at the same time:

  • Two values are equal.
  • One of them is true as a boolean and the other one is false as a boolean.

For example:

let a = 0;
alert( Boolean(a) ); // false
let b = "0";
alert( Boolean(b) ); // true
alert(a == b); // true!
  • Comparison with null and undefined

For a non-strict check ==

There’s a special rule. These two are a “sweet couple”: they equal each other (when compared with ==), but not any other value.

alert( null == undefined ); // true

For maths and other comparisons < > <= >=

null/undefined are converted to numbers: null becomes 0, while undefined becomes NaN.

Compare null with a zero:

alert( null > 0 );  // false
alert( null == 0 ); // false
alert( null >= 0 ); // true

The value undefined shouldn’t be compared to other values, it always returns false, except comparing with null.

alert( undefined > 0 ); // false
alert( undefined < 0 ); // false because undefined gets converted to NaN and NaN is a special numeric value which returns false for all comparisons.
alert( undefined == 0 ); // false because undefined only equals null

Summary

  • There are 8 basic data types in JavaScript.

number for numbers of any kind: integer or floating-point, integers are limited by ±(2^53 — 1).

bigint is for integer numbers of arbitrary length.

string for strings. A string may have zero or more characters, there’s no separate single-character type.

boolean for true/false.

null for unknown values.

undefined for unassigned values.

object for more complex data structures.

symbol for unique identifiers.

  • promptshows a message asking the user to input text. It returns the text or, if the Cancel button or Esc is clicked, null.
  • confirmshows a message and waits for the user to press “OK” or “Cancel”. It returns true for OK and false Cancel/Esc.
  • Numeric Conversion – Occurs in math operations. Can be performed with Number(value). The conversion follows the rules:
undefined — — > NaN NOT 0!!!null — — > 0true or false — — > 1 or 0string — — > whitespaces from the start and end are removed, If the remaining string is empty, the result is 0. Otherwise, the number is “read” from the string. An error gives NaN.
  • Boolean Conversion – Occurs in logical operations. Can be performed with Boolean(value). Follows the rules:
0, null, undefined, NaN, "" — — — -> falseany other value — — —> trueNote a non-empty string is always true.
  • Type conversion tricky parts:

Number(undefined) is NaN , not 0, which is different from Number(null) → 0.

Boolean("0") = trueand space-only strings like Boolean(" ") = trueare both true as a boolean.

Number(undefined); // NaN
Number(null); // 0
Boolean(" "); // true (any non-empty string is true)
  • Operators tricky knowledge:
  1. The subtraction - (like most math operations) only works with numbers, it converts an empty string "" to 0.The subtraction always converts to numbers
  2. null becomes 0 after the numeric conversion.
  3. undefined becomes NaN after the numeric conversion.
  4. Space characters are trimmed off string start and end when a string is converted to a number. Here the whole string consists of space characters, such as \t, \n and a “regular” space between them. So, similarly to an empty string, it becomes 0.
"" + 1 + 0 = "10"
"" - 1 + 0 = -1
null + 1 = 1
undefined + 1 = NaN
" \t \n" - 2 = -2
  • Comparisons

Strings are compared letter-by-letter in the “dictionary” order.

When values of different types are compared, they get converted to numbers (with the exclusion of a strict equality check).

The values null and undefined equal == each other and do not equal any other value.

Be careful when using comparisons like > or < with variables that can occasionally be null/undefined. Checking for null/undefined separately is a good idea.

TBD

--

--

Xinyi Zhao

Frontend Developer, React + Angular girl, gourmet