Loading repository data…
Loading repository data…
NSHoffman / repository
This guide contains brief overview of JavaScript's main concepts and known pitfalls. It might be used as a reference for interview preparation.
This guide contains brief overview of JavaScript's main concepts and known pitfalls. It might be used as a reference for interview preparation.
Variables are references to memory blocks of certain size used to store data. When an undeclared variable is referenced an exception with message
foo is not definedis thrown.
var keywordThe
varkeyword is used to declare function scoped variables in JavaScript. That is, a variable declared usingvaris visible anywhere inside of the enclosing function's body.
function foo() {
var a = 1;
{
// visible anywhere inside foo()
var b = a + 2;
}
function bar() {
// visible only inside bar()
var b = a + 1;
return b;
}
console.log(a + b);
}
foo(); // 4
Once a variable is declared using var, it can be accessed as a property of the window object.
It also works vice versa.
var a = 1;
window.b = 2;
console.log(window.a); // 1
console.log(b) // 2
When a var variable is referenced before declararion its value is evaluated to undefined.
console.log(a); // undefined
var a = 1;
let and const keywordsStarting from ECMAScript 2015 JavaScript allows variable declaration using let and const keywords.
- Unlike variables declared with
varthe ones declared usingletandconstare block scoped, that is, they are visible only inside of the enclosing block or, when it comes to loops, within a single iteration.letandconstvariables cannot be accessed viawindowand are not accessible before declaration statement.- Any attempts to redeclare variables using
let/constkeywords will result inSyntaxError.
The only difference between let and const is that constants cannot be assigned new values in the future.
However, const keyword cannot guarantee that the current value itself will not be modified - it protects only from reassignment and hence constants
must be initialized right in the declaration statement.
let a = 1;
{
console.log(b); // ReferenceError: b is not defined
let b = 2; // visible only inside this block
}
console.log(b); // ReferenceError: b is not defined
const arr = [];
console.log(arr); // []
arr = [1]; // TypeError: Assignment to constant variable
arr.push(1);
console.log(arr); // [1]
Hoisting is JavaScript behaviour of moving variable declarations to the top of the current scope during compilation. Note that only declarations get hoisted, while initialization remains unaffected.
Hoisting is the reason why var variables' values can be accessed before actual declaration statements. It also explains why
those values are evaluated to undefined (because initialization is unaffected by hoisting).
However, values of let and const variables cannot be used before declaration statements as these variables do not get initialized until the declaration.
Destructuring is the feature that has come to JavaScript with ECMAScript 2015 It allows for mapping values of arrays and object fields to new variables.
var { a } = { a: 42 }; // value of 'a' field is assigned to a new variable 'a'
let [b] = [1, 2]; // first value is assigned to 'b'
const { c: foo } = { a: 10, b: 20, c: 30 }; // value of 'c' field is assigned to a new constant 'foo'
console.log(a); // 42
console.log(b); // 1
console.log(foo); // 30
JavaScript has 8 built-in data types. Those are:
number,bigint,boolean,string,null,undefined,symbolandobject.
The
Numbertype is a double-precision 64-bit binary format IEEE 754 value. It is capable of storing positive floating-point numbers betweenNumber.MIN_VALUEandNumber.MAX_VALUEas well as > negative floating-point numbers between-Number.MIN_VALUEand-Number.MAX_VALUE, but it can only safely store integers in the rangeNumber.MIN_SAFE_INTEGERtoNumber.MAX_SAFE_INTEGER.
Besides, number type contains some special values:
Infinity - Positive Infinity, can also be referenced by Number.POSITIVE_INFINITY. Used to refer to numbers greater than Number.MAX_VALUE.-Infinity - Negative Infinity, can also be referenced by Number.NEGATIVE_INFINITY. Used to refer to numbers lower than Number.MIN_VALUE.+0 / -0 - Positive/Negative zeroes, equivalent to unsigned zero 0.NaN - Refers to values that cannot be represented as valid numbers. Can also be referenced by Number.NaN. It's unsafe to use equality operations to determine whether or not a value is NaN -
isNaN() and Number.isNaN() functions must be used for this purpose. isNaN() returns true in case an argument is NaN after performing implicit conversion to number whereas Number.isNaN() does not perform any implicit conversions and returns true only if an argument is NaN.Introduced in ECMAScript 2020,
BigIntis a primitive type that represents an integer value of arbitrary size. It is not limited to a particular bit-width. To representbigIntvaluesnis appended to a numeric literal e.g.1n.
BigInt and Number values are not interchangable: bigInts cannot be used to represent floating-point numbers whereas number cannot be used to represent numeric values of any size. Hence, a type conversion must be performed before any operations between values of these types.
The
Booleantype represents a logical entity having two values -trueandfalse.
The
Stringtype represents textual data and is encoded as a sequence of 16-bit unsigned integer values representing UTF-16 code units. Each element in the string occupies a position in the string which corresponds to a non-negative integer index.
Strings can be defined either by using quotes (' and " - there is no difference between single and double quotes) or by using template string literals (or backticks `).
String templates were introduced in ECMAScript 2015 and allow value interpolation:
console.log(`2 + 2 = ${2 + 2}`); // 2 + 2 = 4
JavaScript strings are immutable. This means that once a string is created, it is not possible to modify it. String methods create new strings based on the content of the current string.
null/undefinedThe Null type has exactly one value, called
null. Note thattypeof nullwill return'object'- that's a known bug that remains solely for backward compatibility reasons.
The Undefined type has exactly one value, calledundefined. Any variable that has not been assigned a value has the valueundefined.
Symbolis a built-in object whose constructor returns a symbol primitive — a Symbol value or just a Symbol — that's guaranteed to be unique.
Symbols are often used to add unique property keys to an object that won't collide with keys any other code might add to the object, and which are hidden from any mechanisms other code will typically use to access the object.
Every Symbol() call is guaranteed to return a unique Symbol. Every Symbol.for("key") call will always return the same Symbol for a given value of "key". When Symbol.for("key") is called, if a Symbol with the given key can be found in the global Symbol registry, that Symbol is returned. Otherwise, a new Symbol is created, added to the global Symbol registry under the given key, and returned.
Objectis a collection of key-value pairs also called properties. Property keys can be values of eitherStringorSymboltypes - keys of any other type will be converted to strings according to these types'toString()method implementation.
Despite the fact thattypeof (function(){})returns'function'- functions are actually objects but with the additional capability of being callable.Arraysare also objects.
Read more about objects: 5.1. Objects
Number conversion rules:
undefined gets converted to NaN.null gets converted to 0.true gets converted to 1, false gets converted to 0.String is parsed as if it contained a valid numeric literal. Parsing failure results in NaN. String is considered valid if:
_ allowed)Infinity literal. Both -Infinity and +Infinity are supported.0 in these cases.BigInt throws TypeError to