YuWebdesign



JavaScript Interview Questions

By YuwebDesign


JavaScript Foundation

JavaScript and Java are completely different languages, both in concept and design.

JavaScript was invented by Brendan Eich in 1995, and became an ECMA standard in 1997.
ECMA-262 is the official name of the standard.
ECMAScript is the official name of the language.

Internal vs. External JavaScript

  1. Internal JavaScript (JS code within html page)
    ⟨script⟩ Javascript code ⟨/script⟩
    

    Old JavaScript examples may use a type attribute:

    ⟨script type="text/javascript"⟩
    

    The type attribute is not required.
    JavaScript is the default scripting language in HTML.

  2. External Script
    ⟨script src="path/to/myScript.js"⟩ Javascript code ⟨/script⟩
    

    Practical when the same code is used in many different web pages.
    External script files cannot contain %lang;script⟩ tags.

JavaScripts in the ⟨body⟩ vs ⟨head⟩

JavaScripts in the ⟨body⟩ vs ⟨head⟩

It is a common practice
to put functions (as well as external script reference)
in the ⟨head⟩ section of an HTML page,
or at the bottom of the page.

Placing scripts at the bottom of the ⟨body⟩ element
improves the display speed,
because script compilation slows down the display.

JavaScript is case sensitive.

  1. JavaScript ignores extra spaces.
    You can add white space to your script to make it more readable.
  2. A good practice is to put spaces around operators
    ( = + – * / )
  3. Use 2 spaces of indentation for code blocks
    (everything inside curly brackets {})

Avoid code lines longer than 80 characters.

If a JavaScript statement does not fit on one line,
the best place to break it is after an operator.

document.getElementById("demo").innerHTML =
"Hello Dolly!";

// single line comment

/* 
   multiple line comment
   multiple line comment
 */ 

It is most common to use single line comments.
Block comments are often used for formal documentation.

\ - escape character
\n - new line
\r - carriage return
\t - horizontal  tabulator
\v - vertical tabulator
\b - backspace
\f - form feed

In addition to “escaping” special characters,
you can break up a code line
within a text string (not a code line)
with a backslash:

document.write("Hello \
World!");

However, this is NOT the preferred method.
It might not have universal support.
Some browsers do not allow spaces behind the \ character.

Concatenate the string instead!

JavaScript Output

Use document.write for testing only.

If you execute it on a loaded HTML document,
all HTML elements will be overwritten.

document.write("<p>My First JavaScript</p>");

<button type="button" onclick="document.write(5 + 6)">Try it</button>

Activate debugging in your browser:

  1. Windows/Linux: F12 or Ctrl + Shift + I
  2. Mac: Command+Option+I
  3. Menu => More tools => Developer Tools => Console

Changing the innerHTML property of an HTML element is a common way to display data in HTML.

document.getElementById("demo").innerHTML = 5 + 6;

JavaScript Operators

  1. A typical arithmetic operation operates on two numbers.
  2. The two numbers can be literals (100 + 2), variables (a + b), or expressions (a*(2+3)).
  3. The numbers (in an arithmetic operation) are called operands.
  4. The operation (to be performed between the two operands) is defined by an operator.

Order of operations
(x + 2) / 3

Operator Description
Addition x = y + 2
Subtraction x = y - 2
Multiplication x = y * 2
Exponentiation x** y
raises the first operand to the power of the second operand

same as Math.pow(x,y)

Division x = y / 2
Modulus Division Remainder
x = y % 2

11 % 9 = 2

Increment x++ //x = x + 1
x = y++
x = ++y
Decrement x = y−−
x = −−y

Read more >>>

Comparison Operators
are used to test for true or false
in logical statements
to determine equality or difference
between variables or values

When comparing a string with a number,

  1. JavaScript will convert the string to a number when doing the comparison.
  2. An empty string converts to 0.
  3. A non-numeric string converts to NaN which is always false.

When comparing numeric strings,
JavaScript performs alphabetic comparison.

E.g., “2” will be greater than “12”,
because (alphabetically) 1 is less than 2:

2 < 12       // true
2 < "12"     // true
"2" < "12"   // false
"2" > "12"   // true
"2" == "12"  // false
Operator Description Example
Equal x == y If (x == y){code}
// check if values are equal
Exactly equal (value and type) x === y If (x === y){code}
// will not equal variables of different types
// (e.g., integer and string)
Not equal x != y
Not equal (different value or different type) x !== y
Greater than x > y
Less than x < y if (age < 18) { x = "Too young"; }
Greater than or equal to x >= y
Less than or equal to x <= y

Read more >>>

  1. Logical Operators
    are typically used with Boolean (logical) values.
    In this case, they return a Boolean value.
  2. However, the && and || operators
    actually return the value of one of the specified operands.
    When used with non-Boolean values, they will return a non-Boolean value.

Truthy and Falsy Values

  1. If a value can be converted to true,
    the value is so-called truthy.
  2. If a value can be converted to false,
    the value is so-called falsy.

    Examples of expressions that can be converted to false are:

    null;
    NaN;
    0;
    empty string ("" or '' or ``);
    undefined
    
Operator Description Example
And exp1 && exp2

If expr1 can be converted to true, returns expr2;
else, returns expr1.

(x < 10 && y > 1)
Or exp1 || exp2

If expr1 can be converted to true, returns expr1;
else, returns expr2.

(x == 5 || y == 5)
Not !exp

Returns false if its single operand can be converted to true;
otherwise, returns true.

!(x == y)

Read more >>>

Ternary Operator
assigns a value to a variable based on some condition.

Syntax:

variableName = (condition) ? value1 : value2

Reads as:

  • if (condition) == true
  • ? value1 means variableName = value1
  • : value2 means else variableName = value2

Example:

voteableAge = (age < 18) ? "Too young" : "Old enough";
// If the variable age < 18, 
// value of voteableAge = "Too young", 
// otherwise voteableAge = "Old enough"

Read more >>>

JavaScript Variables

JavaScript variables are “containers” for storing data values information

In JavaScript, objects and functions are also variables.

Scope determines the accessibility of
variables, objects, and functions
from different parts of the code.

  1. Variables – variable values.
    Variables as symbolic names for values in your application.
  2. Literals – fixed values.
    Literals represent values in JavaScript.
    These are fixed values
    not variables
    that you literally provide in your script.

    Types of literals:

    1. Array literals
      let coffees = ['French Roast', 'Colombian', 'Kona'];
      
    2. Boolean literals
      The Boolean type has two literal values: true and false.
      Do not confuse the primitive Boolean values true and false
      with the true and false values of the Boolean object
    3. Floating-point literals
    4. Numeric literals
    5. Object literals
      An object literal is a list of zero or more pairs
      of property names and associated values of an object,
      enclosed in curly braces ({}).
    6. RegExp literals
    7. String literals

Identifiers are used to name variables (also keywords, functions, and labels).
Names

  1. can contain:
    1. letters,
    2. digits,
    3. underscores,
    4. and dollar signs.
  2. must begin with
    1. a letter,
    2. $
    3. or _
  3. Names are case sensitive
  4. Reserved words (JavaScript keywords) cannot be used as names

JavaScript programmers tend to use camel case that starts with a lowercase letter:

firstName, lastName, masterCard, interCity

JavaScript uses the Unicode Character Set.
Unicode covers (almost) all the characters, punctuations, and symbols in the world.

  1. The lifetime of JavaScript variables starts when they are declared.
  2. Creating a variable in JavaScript is most often referred to as declaring a variable.
  3. Value: in computer programs, variables are often declared without a value.

    The value can be something that has to be calculated,
    or something that will be provided later, like user input.

    An equal sign (assignment operator) is used to assign values to variables.

  4. It’s a good programming practice to declare all variables at the beginning of a script.

Example:

var carName;   
  // After the declaration, the variable is empty 
  // (it has no value). 
  // Variable declared without a value 
  // will have the value undefined.

carName = "Volvo"; 
  // assign a value to the variable

var carName = "Volvo";
  // you can assign a value to the variable
  // when you declare it

var lastName="Doe", age = 30, job = "carpenter";
  // declare many variables in one statement
  // start the statement with var and separate the variables by comma

If you re-declare a JavaScript variable, it will not lose its value:

var carName = "Volvo"; 
var carName;           
// carName will still have the value "Volvo"

Execution context

Execution context
is the environment
in which the JavaScript code is executed.

Environment here means the value of

  1. this,
  2. variables,
  3. objects,
  4. and functions

JavaScript code has access to at a particular time.

3 Types of JavaScript Execution Context
Global execution context Functional execution context Eval
default execution context
in which JS code start its execution
when the file first loads in the browser.

All of the global code
(not inside any function or object)
is executed inside the global execution context.

JS engine is single threaded,
so only one global environment is possible for JS code execution.

created by the JS engine
whenever it finds any function call.

Each function has its own execution context.

Functional execution context has access
to all the code of the global execution context
though vice versa is not applicable.

If the code is executing in strict mode
value of this is undefined
else it is window object
in the function execution context.

Execution context inside eval function.

Execution context stack
is a stack data structure (LIFO – last in first out),
that stores all the execution stacks
created during the life cycle of the script.

Global execution context is present by default
in execution context stack
and it is at the bottom of the stack.

While executing the global execution context code,
if JS engines finds a function call,
it creates a functional execution context for that function
and pushes it on top of the execution context stack.

JS engine executes the function
whose execution context
is at the top of the execution context stack.

Once all the code of the function is executed,
JS engines pop out that function’s execution context
and starts executing the function which is below it.

JavaScript engine creates the execution context in the following two stages:

Creation phase Execution phase
phase in which the JS engine has called a function
but its execution has not started.

JS engine is in the compilation phase
and it just scans over the function code
to compile the code,
it doesn’t execute any code.

JS engines will again scan through the function
to update the variable object
with the values of the variables
and will execute the code.

Creation of the Activation/Variable object

a special object in JS
which contains

  1. all the variables
    for each variable
    (including function arguments),
    JS engine will create a property
    on the activation/variable object
    and will initialize it with undefined.
  2. function arguments

    Activation/variable object
    contains the argument object
    which has details
    about the arguments of the function.

    It will have a property name (not the value)
    for each of the variables and functions
    which are declared inside the current function.

    It will also have the length property
    indicating the total number of arguments in the function.

  3. inner functions declaration information

    When JS engine encounters a function definition
    inside the current function,
    it will create a new property
    by the name of the function.

    Function definitions in the creation phase
    are stored in heap memory,
    they are not stored
    in the execution context stack.

    Function name property points
    to its definition in the heap memory.

Creation of the scope chain
Once the activation object is created,
the JS engine initializes the scope chain

which is a list of all the variables objects
inside which the current function exists.

Scope chain includes
the variable object of the

  1. global execution context
  2. current function

Initialization of the value of this

According to Wikipedia,
Scope is an important component of name resolution,
which is in turn fundamental to language semantics.

Name resolution (including scope) varies between programming languages,
and within a programming language, varies by type of entity;
the rules for scope are called scope rules or scoping rules.

Together with namespaces, scoping rules are crucial in modular programming,
so a change in one part of the program does not break an unrelated part.

In computer programming,
the scope of a name binding
(an association of a name to an entity, e.g. variable)
is the region of a computer program
where the binding is valid:
where the name can be used to refer to the entity.

Such a region is referred to as a scope block.

In other parts of the program
the name may refer to a different entity
(it may have a different binding),
or to nothing at all (it may be unbound).

The scope of a binding is also known as the visibility of an entity.

Scope determines the accessibility (visibility) of the variables.

According to MDN, scope
is the current context of execution.

The context in which values and expressions
are “visible” or can be referenced.

If a variable or other expression
is not “in the current scope,”
then it is unavailable for use.

Scopes can also be layered in a hierarchy,
so that child scopes have access to parent scopes,
but not vice versa.

A function serves as a closure in JavaScript,
and thus creates a scope,
so that (for example) a variable
defined exclusively within the function
cannot be accessed from outside the function
or within other functions.

The scope chain
is a list of all the variable objects
of functions
inside which the current function exists.

Scope chain also consists
of the current function execution object.

In JavaScript there are two types of scope:

Local/Function scope Global scope
  1. JavaScript has function scope: each function creates a new scope.
  2. A variable declared within a JavaScript function becomes local.

    Local variables have function/local scope:
    function arguments (parameters) work as local variables inside functions.

  3. Variables defined inside a function
    are not accessible (visible) from outside the function.
    They can only be accessed from within the function.
  4. Variables declared outside a function, become global.
  5. Since local variables are only recognized inside their functions,
    variables with the same name can be used in different functions.
  6. Local variables are created when a function starts, and deleted as soon as the function is completed.
  1. In a programming environment,
    the global scope is the scope that contains,
    and is visible in, all other scopes.
  2. In client-side JavaScript,
    the global scope is generally the web page
    inside which all the code is being executed.
  3. A global variable has global scope:
    All scripts and functions on a web page can access it.
  4. In a web browser, global variables are deleted when you close the browser window (or tab),
    but remain available to new pages loaded into the same window.
  5. Do NOT create global variables unless you intend to.

    Your global variables (or functions) can overwrite window variables (or functions).
    Any function, including the window object, can overwrite your global variables and functions.

// code here can NOT use carName

function myFunction() {
  var carName = "Volvo";
  // code here CAN use carName
}

// code here can NOT use carName
<p id="demo"></p>
<script>
myFunction();
// code here can use carName as a global variable
document.getElementById("demo").innerHTML = 
"I can display " + carName;
function myFunction() {
  carName = "Volvo";
}
</script>  // I can display Volvo
Local variables
exist only within the function body
of which they are defined
and will have a different scope
for every call of that function.

There it is subject for
value assignment, retrieval, and manipulation
only within that call
and is not accessible outside of that scope.

Any defined global variable,
meaning any variable
declared outside of a function body
will live throughout runtime
and can be accessed and altered
in any scope.
Automatically Global

If you assign a value to a variable
that has not been declared,
it will automatically become a global variable.

Global Variables in HTML vs. JavaScript

  1. With JavaScript, the global scope is the complete JavaScript environment.
  2. In HTML, the global scope is the window object.
    All global variables belong to the window object
<p id="demo"></p>

<script>
var carName = "Volvo";

// code here can use window.carName
document.getElementById("demo").innerHTML = 
"I can display " + window.carName;

</script>
Strict Mode
All modern browsers support running JavaScript in “Strict Mode”.
Global variables are not created automatically in “Strict Mode”.

Scope can vary from as little as a single expression to as much as the entire program, with many possible gradations in between.

The simplest scoping rule is global scope—all entities are visible throughout the entire program.

The most basic modular scoping rule is two-level scoping, with a global scope anywhere in the program, and local scope within a function.

  1. Expression scope
    Many languages, especially functional languages, offer a feature called let-expressions, which allow a declaration’s scope to be a single expression. This is convenient if, for example, an intermediate value is needed for a computation.
  2. Block scope
    Blocks are primarily used for control flow,
    such as with if, while, and for loops,
    and in these cases block scope means
    the scope of variable depends on the structure
    of a function’s flow of execution.

    If a block is used to set the value of a variable,
    block scope requires that the variable
    be declared outside of the block.
    This complicates the use of conditional statements with single assignment.

  3. Function scope
    a variable whose scope ends (that goes out of context) when the function returns. In most cases the lifetime of the variable is the duration of the function call—it is an automatic variable, created when the function starts (or the variable is declared), destroyed when the function returns.

    Importantly, in lexical scoping a variable with function scope has scope only within the lexical context of the function: it moves out of context when another function is called within the function, and moves back into context when the function returns—called functions have no access to the local variables of calling functions, and local variables are only in context within the body of the function in which they are declared.

    In languages with lexical scoping and nested functions, local variables are in context for nested functions, since these are within the same lexical context, but not for other functions that are not lexically nested. A local variable of an enclosing function is known as a non-local variable for the nested function. Function scope is also applicable to anonymous functions.

  4. File scope
  5. Module scope
  6. Global scope

    A declaration has global scope if it has effect throughout an entire program. Variable names with global scope — called global variables — are frequently considered bad practice, at least in some languages, due to the possibility of name collisions and unintentional masking, together with poor modularity, and function scope or block scope are considered preferable. However, global scope is typically used (depending on the language) for various other sorts of identifiers, such as names of functions, and names of classes and other data types. In these cases mechanisms such as namespaces are used to avoid collisions.

    The use of local variables — of variable names with limited scope, that only exist within a specific function — helps avoid the risk of a name collision between two identically named variables.

Read more >>>

A fundamental distinction in scoping is what “part of a program” means.

  1. For most programming languages,
    “part of a program” refers to “portion of the source code (area of text)”,
    and is known as lexical scope.

    In languages with lexical scope (also called static scope), name resolution depends on the location in the source code and the lexical context, which is defined by where the named variable or function is defined.

    With lexical scope a variable’s definition is resolved
    by first looking for a local definition of a variable,
    searching its containing block or function,
    then if that fails searching the outer containing block.

    In lexically scoped languages,
    scope for closures can be confusing to the uninitiated,
    as these depend on the lexical context
    where the closure is defined, not where it is called.

  2. In some languages, however, “part of a program” refers to “portion of run time (time period during execution)”, and is known as dynamic scope.

    In languages with dynamic scope
    the name resolution depends upon the program state
    when the name is encountered
    which is determined by the execution context or calling context.

    in dynamic scoping (or dynamic scope), if a variable name’s scope is a certain function, then its scope is the time-period during which the function is executing: while the function is running, the variable name exists, and is bound to its value, but after the function returns, the variable name does not exist.

    With dynamic scope,
    first local definition of a variable,
    then the calling function is searched,
    then the function which called that calling function,
    and so on, progressing up the call stack.

Lexical resolution can be determined at compile time, and is also known as early binding, while dynamic resolution can in general only be determined at run time, and thus is known as late binding.

# bash language
$ x=1

$ function g () { echo $x ; x=2 ; }
$ function f () { local x=3 ; g ; }

$ f # does this print 1, or 3?
3
$ echo $x # does this print 1, or 2?

This means that if function f invokes a separately defined function g,

then under lexical scoping,
function g does not have access
to f’s local variables
(assuming the text of g is not inside the text of f),

while under dynamic scoping,
function g does have access to f’s local variables
(since g is invoked during the invocation of f).

JavaScript has lexical scope

Example from Kyle Simpson’s book — You don’t know JS, Scope&Closure:

Assume that, if Javascript had dynamic scope, when foo() is executed, theoretically the code below would result 3 as the output.

function foo() {
	console.log( a ); // 3  (not 2!)
}

function bar() {
	var a = 3;
	foo();
}

var a = 2;

bar();

When foo() cannot resolve the variable reference for a,
instead of stepping up the nested (lexical scope) scope chain,
it walks up the call-stack,
to find where foo() was called from.

Since foo() was called from bar()
it checks the variables in scope for bar(),
and finds an a there with value 3.

Javascript does not have dynamic scope.
It has lexical scope.

Dynamic scope is a near cousin to another mechanism called “this” in Javascript.
But note that “this” mechanism is kind of like dynamic scope.

The key contrast: lexical scope is write-time, whereas dynamic scope (and this!) are runtime. Lexical scope cares where a function was declared, but dynamic scope cares where a function was called from.

Finally: this cares how a function was called, which shows how closely related the this mechanism is to the idea of dynamic scoping.

JavaScript has simple scoping rules, but variable initialization and name resolution rules can cause problems, and the widespread use of closures for callbacks means the lexical environment of a function when defined (which is used for name resolution) can be very different from the lexical environment when it is called (which is irrelevant for name resolution). JavaScript objects have name resolution for properties, but this is a separate topic.

JavaScript has lexical scoping nested at the function level, with the global scope being the outermost scope. This scoping is used for both variables and for functions (meaning function declarations, as opposed to variables of function type). Block scoping with the let and const keywords is standard since ECMAScript 6. Block scoping can be produced by wrapping the entire block in a function and then executing it; this is known as the immediately-invoked function expression (IIFE) pattern.

While JavaScript scoping is simple—lexical, function-level—the associated initialization and name resolution rules are a cause of confusion. Firstly, assignment to a name not in scope defaults to creating a new global variable, not a local one. Secondly, to create a new local variable one must use the var keyword; the variable is then created at the top of the function, with value undefined and the variable is assigned its value when the assignment expression is reached:

A variable with an Initialiser is assigned the value of its AssignmentExpression when the VariableStatement is executed, not when the variable is created.
This is known as variable hoisting—the declaration, but not the initialization, is hoisted to the top of the function. Thirdly, accessing variables before initialization yields undefined, rather than a syntax error. Fourthly, for function declarations, the declaration and the initialization are both hoisted to the top of the function, unlike for variable initialization. For example, the following code produces a dialog with output undefined, as the local variable declaration is hoisted, shadowing the global variable, but the initialization is not, so the variable is undefined when used:

a = 1;
function f() {
    alert(a);
    var a = 2;
}
f();

Further, as functions are first-class objects in JavaScript and are frequently assigned as callbacks or returned from functions, when a function is executed, the name resolution depends on where it was originally defined (the lexical environment of the definition), not the lexical environment or execution environment where it is called. The nested scopes of a particular function (from most global to most local) in JavaScript, particularly of a closure, used as a callback, are sometimes referred to as the scope chain, by analogy with the prototype chain of an object.

Closures can be produced in JavaScript by using nested functions, as functions are first-class objects. Returning a nested function from an enclosing function includes the local variables of the enclosing function as the (non-local) lexical environment of the returned function, yielding a closure.

function newCounter() {
    // return a counter that is incremented on call (starting at 0)
    // and which returns its new value
    var a = 0;
    var b = function() { a++; return a; };
    return b;
}

c = newCounter();
alert(c() + ' ' + c());  // outputs "1 2"

Closures are frequently used in JavaScript, due to being used for callbacks. Indeed, any hooking of a function in the local environment as a callback or returning it from a function creates a closure if there are any unbound variables in the function body (with the environment of the closure based on the nested scopes of the current lexical environment, or “scope chain”); this may be accidental. When creating a callback based on parameters, the parameters must be stored in a closure, otherwise it will accidentally create a closure that refers to the variables in the enclosing environment, which may change.

Name resolution of properties of JavaScript objects is based on inheritance in the prototype tree—a path to the root in the tree is called a prototype chain—and is separate from name resolution of variables and functions.

Read more >>>

When discussing scope, there are three basic concepts: scope, extent, and context.

“Scope” and “context” in particular are frequently confused: scope is a property of an identifier, and is fixed, while context is a property of a program, which varies by position.

More precisely, context is a property of a position in the program, either a position in the source code (lexical context) or a point during run time (execution context, runtime context, or calling context).

Execution context consists of lexical context (at the current execution point) plus additional runtime state such as the call stack. Thus, when the execution point of a program is in a variable name’s scope, the “variable (name) is in context” (meaning “in the context at this point”), and when the execution point “exits a variable (name)’s scope”, such as by returning from a function, “the variable (name) goes out of context”.

Narrowly speaking, during execution a program enters and exits various scopes, and at a point in execution identifiers are “in context” or “not in context”, hence identifiers “come into context” or “go out of context” as the program enters or exits the scope—however in practice usage is much looser.

Scope is a source-code level concept, and a property of identifiers, particularly variable or function names—identifiers in the source code are references to entities in the program—and is part of the behavior of a compiler or interpreter of a language. As such, issues of scope are similar to pointers, which are a type of reference used in programs more generally.

For entities such as variables, scope is a subset of lifetime (also known as extent)—a name can only refer to a variable that exists (possibly with undefined value), but variables that exist are not necessarily visible: a variable may exist but be inaccessible (the value is stored but not referred to within a given context), or accessible but not via the given name, in which case it is out of context (the program is “out of the scope of the name”). In other cases “lifetime” is irrelevant—a label (named position in the source code) has lifetime identical with the program (for statically compiled languages), but may be in or out of context at a given point in the program, and likewise for static variables—a static global variable is in context for the entire program, while a static local variable is only in context within a function or other local context, but both have lifetime of the entire run of the program.

Determining which entity an identifier refers to is known as name resolution or name binding (particularly in object-oriented programming), and varies between languages. Given an identifier, the language (properly, the compiler or interpreter) checks all entities that are in context for matches; in case of ambiguity (two entities with the same name, such as a global and local variable with the same name), the name resolution rules are used to distinguish them. Most frequently, name resolution relies on an “inner-to-outer” rule: names implicitly resolves to the narrowest relevant context.

When two identical identifiers are in context at the same time, referring to different entities, one says that name masking is occurring, where the higher-priority name (usually innermost) is “masking” the lower-priority name. At the level of variables, this is known as variable shadowing. Due to the potential for logic errors from masking, some languages disallow or discourage masking, raising an error or warning at compile time or run time.

JavaScript

When the JavaScript interpreter initially executes code,
it first enters into a global execution context by default.

Each invocation of a function from this point on
will result in the creation
of a new execution context.

This is where confusion often sets in,
the term “execution context”
is actually for all intents and purposes
referring more to scope
and not context as previously discussed.

Every function invocation has both a scope
and a context associated with it.

Fundamentally, scope is function-based
while context is object-based.

Scope pertains to the variable access
of a function when it is invoked
and is unique to each invocation.

Context is the value of the this keyword
which is a reference to the object
that “owns” the currently executing code.

Each time a new execution context is created
it is appended to the top of the execution stack.

The browser will always execute
the current execution context
that is atop the execution stack.

Once completed,
it will be removed from the top of the stack
and control will return
to the execution context below.

An execution context can be divided
into a creation and execution phase.

In the creation phase,
the interpreter will first create a variable object
(also called an activation object)
that is composed of all the variables,
function declarations, and arguments
defined inside the execution context.

From there the scope chain is initialized next
(contains the variable object
for every execution context
in the execution stack.
It is used for determining variable access
and identifier resolution.),
and the value of this is determined last.

Then in the execution phase,
code is interpreted and executed.

A closure
is the combination of a function
and the lexical environment
within which that function was declared.

This environment consists of any local variables
that were in-scope
at the time the closure was created.

In other words, a closure gives you access
to an outer function’s scope from an inner function.

In JavaScript, closures are created
every time a function is created,
at function creation time.

Accessing variables
outside of the immediate lexical scope
creates a closure.

A closure is formed
when a nested function
is defined inside of another function,
allowing access to the outer functions variables.

Returning the nested function
allows you to maintain access
to the local variables, arguments,
and inner function declarations
of its outer function.

This encapsulation allows us
to hide and preserve the execution context
from outside scopes
while exposing a public interface
and thus is subject to further manipulation.

function foo() {
    var parentVariable = 'private variable';
    return function() {
        return parentVariable;
    }
}

var getParentVariable = foo();
getParentVariable() // "private variable"
Closures and OOPs

Closures are useful because they let you associate data (the lexical environment) with a function that operates on that data. This has obvious parallels to object-oriented programming, where objects allow you to associate data (the object’s properties) with one or more methods.

  1. Consequently, you can use a closure anywhere that you might normally use an object with only a single method.

    Situations where you might want to do this are particularly common on the web. Much of the code written in front-end JavaScript is event-based. You define some behavior, and then attach it to an event that is triggered by the user (such as a click or a keypress). The code is attached as a callback (a single function that is executed in response to the event).

  2. Emulating private methods with closures
    Languages such as Java allow you to declare methods as private, meaning that they can be called only by other methods in the same class.

    JavaScript does not provide a native way of doing this, but it is possible to emulate private methods using closures. Private methods aren’t just useful for restricting access to code. They also provide a powerful way of managing your global namespace.

    Closures defining public functions that can access private functions and variables follow the Module Design Pattern, where is a single lexical environment is shared by several functions.

Module Pattern

One of the most popular types of closures
is what is widely known as the module pattern;
it allows you to emulate
public, private, and privileged members:

var Module = (function() {
    var privateProperty = 'foo';

    function privateMethod(args) {
        // do something
    }

    return {

        publicProperty: '',

        publicMethod: function(args) {
            // do something
        },

        privilegedMethod: function(args) {
            return privateMethod(args);
        }
    };
})();

The module acts as if it were a singleton,
executed as soon as the compiler interprets it,
hence the opening and closing parenthesis
at the end of the function.

The only available members
outside of the execution context of the closure
are your public methods and properties
located in the return object
(Module.publicMethod for example).

However, all private properties and methods
will live throughout the life of the application
as the execution context is preserved,
meaning variables are subject to further interaction
via the public methods.

immediately-invoked function expression (IIFE)

Another type of closure
is what is called
an immediately-invoked function expression (IIFE)
which is nothing more
than a self-invoked anonymous function
executed in the context of the window:

(function(window) {
          
    var foo, bar;

    function private() {
        // do something
    }

    window.Module = {

        public: function() {
            // do something 
        }
    };

})(this);

This expression is most useful
when attempting to preserve the global namespace
as any variables declared within the function body
will be local to the closure
but will still live throughout runtime.

This is a popular means of encapsulating source code
for applications and frameworks,
typically exposing a single global interface
in which to interact with.

ryanmorr >>>
mdn >>>

Every closure has three scopes:

  1. Local Scope (Own scope)
  2. Outer Functions Scope
  3. Global Scope

A common mistake is not realizing that, in the case where the outer function is itself a nested function, access to the outer function’s scope includes the enclosing scope of the outer function—effectively creating a chain of function scopes. To demonstrate, consider the following example code.

// global scope
var e = 10;
function sum(a){
  return function(b){
    return function(c){
      // outer functions scope
      return function(d){
        // local scope
        return a + b + c + d + e;
      }
    }
  }
}

console.log(sum(1)(2)(3)(4)); // log 20

without anonymous functions

// global scope
var e = 10;
function sum(a){
  return function sum2(b){
    return function sum3(c){
      // outer functions scope
      return function sum4(d){
        // local scope
        return a + b + c + d + e;
      }
    }
  }
}

var s = sum(1);
var s1 = s(2);
var s2 = s1(3);
var s3 = s2(4);
console.log(s3) //log 20

In this example there is a series of nested functions,
all of which have access to the outer functions’ scope.
In this context, we can say that closures have access to all outer function scopes.

mdn >>>

Variable scope

Global Variable
When you declare a variable outside of any function,
it is called a global variable,
because it is available to any other code
in the current document.

Local Variable
When you declare a variable within a function,
it is called a local variable,
because it is available only within that function.

Block Statement Scope
In JavaScript before ECMAScript 2015
there is no block statement scope.

Rather, a variable (var) declared within a block

  1. is local to the function that the block resides within
    (or the function context if the code is part of a function),
  2. within a block (e.g. if statement block)
    the scope of var is the global context
    (the scope of var is not limited to the immediate if statement block.

ECMAScript 6 (ES6/ES2015)
introduced the let and const keywords
that support the declaration
of block scope local variables.

This means the variable
will be confined to the scope
of a block that it is defined in
(e.g., if statement or for loop)
and will not be accessible
outside of the opening and closing curly braces
of the block.

This is contrary to var declarations
which are accessible outside blocks
they are defined in.

The difference between let and const
is that a const declaration is,
as the name implies,
constant – a read-only reference to a value.

This does not mean the value is immutable,
just that the variable identifier cannot be reassigned.

The JavaScript this keyword refers to the object it belongs to.

It has different values depending on where it is used:

  1. In a method, this refers to the owner object.
  2. Alone, this refers to the global object.
  3. In a function, this refers to the global object
    (global context or window object in the browser).
  4. In a function, in strict mode, this is undefined.
  5. In an event, this refers to the element that received the event.
  6. Explicit Function Binding:
    methods like call(), and apply() can refer this to any object.
  7. When used alone, the owner is the Global object, so this refers to the Global object
    (global context or window object in the browser).

    In strict mode, when used alone, this also refers to the Global object

this in a Method

Context is most often determined
by how a function is invoked.

When a function is called
as a method of an object,
this is set to the object
the method is called on
(the “owner” of the method).

var person = {
  firstName: "John",
  lastName : "Doe",
  id     : 5566,
  fullName : function() {
    return this.firstName + " " + this.lastName;
  }
};
// this represents the person object
var obj = {
    foo: function() {
        return this;   
    }
};

obj.foo() === obj; // true

The same principle applies
when invoking a function with the new operator
to create an instance of an object.

When invoked in this manner,
the value of this within the scope of the function
will be set to the newly created instance:

var obj = {
    foo: function() {
        return this;   
    }
};

obj.foo() === obj; // true

The same principle applies
when invoking a function
with the new operator
to create an instance of an object.

The value of this
within the scope of the function
will be set to the newly created instance:

function foo() {
    alert(this);
}

foo() // window
new foo() // foo

JavaScript Declarations are Hoisted

Hoisting
is JavaScript’s default behavior
of moving all declarations to the top of the current scope
(to the top of the current statement or the current function).

Variable Hoisting
  1. var can be declared after it has been used.

    In other words; a variable can be used before it has been declared.

    JavaScript initializations are not hoisted

    Variables (var) that are hoisted return a value of undefined.

    So even if you declare and initialize var
    after you use or refer to this variable,
    it still returns undefined.

    var x = 5;  // Initialize x
    
    elem = document.getElementById("demo");  // Find an element 
    elem.innerHTML = "x is " + x + " and y is " + y;  // Display x and y
    
    var y = 7;  // Initialize y
    
    // x is 5 and y is undefined
    
    // y has been declared before it is used, 
    // but because initializations are not hoisted, 
    // the value of y is undefined.
    

    same as

    var x = 5; // Initialize x
    var y;   // Declare y
    elem = document.getElementById("demo"); // Find an element 
    elem.innerHTML = x + " " + y;  // Display x and y
    y = 7;   // Assign 7 to y
    
    // x = 5, y = undefined
    
    var myvar = 'my value';
     
    (function() {
      console.log(myvar); // undefined
      var myvar = 'local value';
    })();
    

    same as

    var myvar = 'my value';
     
    (function() {
      var myvar;
      console.log(myvar); // undefined
      myvar = 'local value';
      console.log(myvar); // local value
    })();
    // because myvar = 'local value' is initialized after logging it defaults to undefined 
    // and overwrites 'my value' 
    

    Because of hoisting, all var statements in a function
    should be placed as near to the top of the function as possible.

  2. let and const are are hoisted but not initialized.

    Referencing let/const in the block before the variable declaration
    results in a ReferenceError.

    console.log(x); // ReferenceError
    let x = 3;
    

Read more >>>

Function hoisting

Only function declarations are hoisted
but not the function expressions
(function expression can be stored in a variable).

Function declarations
load before any code is executed

while Function expressions
load only when the interpreter reaches that line of code.

Similar to the var statement,
function declarations are hoisted to the top of other code.

Function expressions aren’t hoisted,
which allows them to retain a copy of the local variables
from the scope where they were defined.

Benefits of Function Expressions

There are several different ways that function expressions become more useful than function declarations.
As closures
As arguments to other functions
As Immediately Invoked Function Expressions (IIFE)

Function declaration:

foo(); // "bar"

function foo() {
  console.log('bar');
}

Function expression:

baz(); // TypeError: baz is not a function

var baz = function() {
  console.log('bar2');
};

Read more >>>

Bind

ECMAScript 5 (ES5) introduced the Function.prototype.bind method
that is used for manipulating context.

The bind() method creates a new function that, when called,
has its this keyword set to the provided value,
with a given sequence of arguments
preceding any provided when the new function is called.

It returns a new function
which is permanently bound to the first argument of bind
regardless of how the function is being used.

It works by using a closure
that is responsible for redirecting the call in the appropriate context.

It is commonly used where context is commonly lost;
object-orientation and event handling.

Bind is a solution to the problem
of how to keep the context of “this” within another function.

var foo = {
    x: 3
}

var bar = function(){
    console.log(this.x);
}

bar(); // undefined

var boundFunc = bar.bind(foo);

boundFunc(); // 3
//created a new function with this set to foo — not the global scope

Call and Apply

These two methods inherent to all functions
allow you to execute any function in any desired context.
With call() and apply(), an object can use a method belonging to another object.

This makes for incredibly powerful capabilities.

The call function requires the arguments to be listed explicitly
while the apply function allows you to provide the arguments as an array.

The call() method is a predefined JavaScript method.
It can be used to invoke (call) a method with an owner object as an argument (parameter).

var person = {
  fullName: function() {
    return this.firstName + " " + this.lastName;
  }
}

var person1 = {
  firstName:"John",
  lastName: "Doe"
}

var person2 = {
  firstName:"Mary",
  lastName: "Doe"
}

person.fullName.call(person1);  // "John Doe"
person.fullName.apply(person1); // "John Doe"
var person = {
  fullName: function(city, country) {
    return this.firstName + " " + this.lastName + "," + city + "," + country;
  }
}

var person1 = {
  firstName:"John",
  lastName: "Doe"
}

person.fullName.call(person1, "Oslo", "Norway");
person.fullName.apply(person1, ["Oslo", "Norway"]);
//John Doe,Oslo,Norway

The result of both calls is exactly the same.

The difference is:

  1. The call() method takes arguments separately.
  2. The apply() method takes arguments as an array.

  1. JavaScript in strict mode (“use strict”)
    does not allow variables to be used
    if they are not declared.
  2. Objects are variables too.
    Using an object, without declaring it, is not allowed.
  3. Deleting a variable (or object), or a function is not allowed.
  4. Duplicating a parameter name is not allowed.
  5. Octal numeric literals (010) or escape characters (var x = “\010″;) are not allowed
  6. In function calls like f(), the this value was the global object. In strict mode, it is now undefined.
  7. Strict mode is declared by adding “use strict”; to the beginning of a script or a function.
  8. The “use strict” directive is only recognized at the beginning of a script or a function.
  9. Declared at the beginning of a script, it has global scope (all code in the script will execute in strict mode).
  10. Declared inside a function, it has local scope (only the code inside the function is in strict mode).

JavaScript Functions

A function is a block of code
designed to perform a particular task
that will be executed when when “called” for.

  1. A function keyword declares a function
  2. The parentheses may include parameter names separated by commas:
    (parameter1, parameter2, …)
  3. The code to be executed, by the function, is placed inside curly brackets: {}
  4. Function parameters are listed inside the parentheses () in the function definition.
  5. Function arguments are the values received by the function when it is invoked.
  6. Inside the function, the arguments (the parameters) behave as local variables.
function name(parameter1, parameter2, parameter3) {
  // code to be executed
}

  1. The code inside the function will execute when “something” invokes (calls) the function (call = invoke = run a function):
    1. When an event occurs (when a user clicks a button)
    2. When it is invoked (called) from JavaScript code
    3. Automatically (self invoked)
  2. When you call a function, you can pass along some values to it,
    these values are called arguments or parameters.
  3. Accessing a function without () will return the function definition instead of the function result
functionName(argument1,argument2)

  1. Functions often compute a return value.
    Function returns the specified return value
    back to the “caller” (to where the call was made).
  2. The function-call will be replaced with the return value.
  3. When JavaScript reaches a return statement,
    the function will stop executing.
  4. If the function was invoked from a statement,
    JavaScript will “return”
    to execute the code after the invoking statement.
function myFunction()
{
var x=5;
return x;
}
var myVar=myFunction();
// variable x holds the value 5,
// which is what the function "myFunction()" returns.

// You can also use the return value without storing it as a variable:
document.getElementById("demo").innerHTML=myFunction();

// Calculate the product of two numbers, and return the result:
function myFunction(a,b)
{
return a*b;
}
document.getElementById("demo").innerHTML=myFunction(4,3);

Functions can be used the same way as variables,
in all types of formulas, assignments, and calculations.

var x = toCelsius(77); // variable stores return value of a function
var text = "The temperature is " + x + " Celsius";

var text = "The temperature is " + toCelsius(77) + " Celsius";
// function used directly, as a variable value

  1. Scope safety
    Until arrow functions,
    every new function defined its own this value
    (a new object in the case of a constructor,
    undefined in strict mode function calls,
    the base object if the function is called as an “object method”, etc.).

    An arrow function does not create its own this,
    the this value of the enclosing execution context is used.

  2. Compactness
    Arrow functions are easier to read and write.
  3. Clarity
    When almost everything is an arrow function,
    any regular function immediately sticks out for defining the scope.

    A developer can always look up the next-higher function statement
    to see what the Object is.

A pure function is a function
that doesn’t depend on
and doesn’t modify
the states of variables out of its scope.

Essentially, this means
that a pure function will always return the same result
given same parameters.

Memoization
stores the arguments of each function call
along with the result.

If the function is called again with the same arguments,
return the precomputed result,
rather than running the function again.

Control Flow

  1. An expression is a combination of
    1. values,
    2. variables,
    3. and operators,

    which computes to a value.

  2. The values can be of various types, such as numbers and strings.
  3. The computation is called an evaluation.
5 * 10  // evaluates to 50
x * 10  // contains variable
"John" + " " + "Doe"  // evaluates to "John Doe"

A code block is a block of code between { and }.

If statement has only one single line of code, the braces can be omitted:

  if (i == someReason) console.log('no braces are ok here');

Syntax:
To label JavaScript statements,
precede the statements with a colon:

label:
statements

The break and the continue statements
are the only JavaScript statements
that can “jump out of” a code block.

  1. continue labelName;
    (With or without a label reference)
    can only be used inside a loop.
  2. break labelName;
    • Without a label reference,
      can only be used inside a loop or a switch.
    • With a label reference,
      can be used to “jump out of”
      any JavaScript code block
cars=["BMW","Volvo","Saab","Ford"];
list: 
{
document.write(cars[0] + "
"); document.write(cars[1] + "
"); break list; document.write(cars[2] + "
"); document.write(cars[3] + "
"); } // BMW // Volvo

  1. A computer program is a list of “instructions” to be “executed” by a computer.
  2. In HTML, JavaScript programs are executed by the web browser.
  3. JavaScript statements are “commands” to the browser.
  4. Javascript has single threaded (one command at a time)
    synchronous execution (only one thing is happening at a time)
  5. JavaScript statements are composed of:
    1. Values,
    2. Operators,
    3. Expressions,
    4. Keywords,
    5. and Comments
  6. Ending statements with semicolon is not required, but highly recommended.
var x, y, z;    // Statement 1
x = 5;          // Statement 2
y = 6;          // Statement 3
z = x + y;      // Statement 4

  1. JavaScript statements often start with a keyword
    to identify the JavaScript action to be performed.
  2. JavaScript keywords are reserved words.
    Reserved words cannot be used as names for variables.
Statement Keyword Description
break Terminates a switch or a loop
continue Jumps out of a loop and starts at the top
debugger Stops the execution of JavaScript
and calls (if available) the debugging function
do … while Executes a block of statements,
and repeats the block,
while a condition is true
for Marks a block of statements to be executed,
as long as a condition is true
function Declares a function
if .. else A conditional statement
that represents a block of code to be executed
if condition is either true or false
switch A conditional statement
that specifies several alternative blocks of code
to be executed depending on different cases
return Exits a function
try … catch Implements error handling to a block of statements
var Declares a variable

  1. switchStatement
    a conditional statement
    that specifies several alternative blocks of code
    to be executed depending on different cases.
  2. The switch expression is evaluated once.
  3. The value of the expression is compared with the values of each case.

    Switch cases use strict comparison (===).
    The values/operands must be of the same type to match.

  4. Switching Details
    1. If there is a match, the associated block of code is executed.
    2. If multiple cases matches a case value, the first case is selected.
    3. If no matching cases are found, the program continues to the default label.
    4. If no default label is found, the program continues to the statement(s) after the switch.
  5. If you omit the break statement,
    the next case will be executed
    even if the evaluation does not match the case.
  6. Common Code Blocks
    different switch cases can use the same code.

Syntax:

switch(expression) {
  case labelName1:
    // execute code block 1
    break;  // break prevents the code 
            // from running into the next case automatically
  case labelName2:
    // execute code block 2
    break;
  default:
    // code block tells what to do 
    // if there is no case match code to be executed
    //  if (expression) is different from case 1 and 2
    // does not have to be the last case in a switch block
    break;  // remember to end the default case with a break
}

Example 1:

var day = new Date().getDay();
switch (day) {
case 4:  // case 4 and 5 share the same code block
case 5:
    text = "Soon it is Weekend";
    break; 
case 6:
  x = "Today is Saturday";
  break;
case 0:
  x = "Today is Sunday";
  break;
default:
  x = "Looking forward to the Weekend";
  break;
}

Example 2:

switch (fruits) {
 case  "Banana":
    alert("Hello")
    break;
case  "Apple":
    alert("Welcome")
    break;    
}

if .. else

a conditional statement
that represents a block of code to be executed
if condition is either true or false.

Syntax:

if (condition1) {
  //  block of code to be executed if condition1 is true
} else if (condition2) {
  //  block of code to be executed if the condition1 is false and condition2 is true
} else {
  //  block of code to be executed if the condition1 is false and condition2 is false
}

Break Statement
  1. breaks the loop and continues executing the code after the loop (if any)
  2. is used to “jump out” of
    1. a switch() statement
    2. or a loop.
for (i = 0; i < 10; i++)   {
  if (i == 3)  {
    break;
    }
  x = x + "The number is " + i + "</br>";
  }

Continue Statement
breaks/"jumps over" one iteration (in the loop),
if a specified condition occurs,
and continues with the next iteration in the loop.

for (i = 0; i <= 10; i++) {
 if (i == 3) continue;    // skips the value of 3
 x = x + "The number is " + i + "</br>";
}

Example Explanation
Syntax:

for (statement 1; statement 2; statement 3)  {
  the code block to be executed
  }

Example:

for (var i = 0 ; i < cars.length; i++)
{ 
  document.write(cars[i] + "</br>");
}

/* Instead of writing:
   * document.write(cars[0] + "</br>"); 
   * document.write(cars[1] + "</br>"); 
   * document.write(cars[2] + "</br>"); 
   * document.write(cars[3] + "</br>"); 
   * document.write(cars[4] + "</br>"); 
   *document.write(cars[5] + "</br>"); 
*/

Example:

var fruits, text, fLen, i;
fruits = ["Banana", "Orange", "Apple", "Mango"];
fLen = fruits.length;

text = "<ul>";

for (i = 0; i < fLen; i++) {
  text += "<li>" + fruits[i] + "</li>";
}

text += "</ul>";
For Loop
loops through a block of code
a number of times,
as long as a condition is true.

Often this is the case when working with arrays

Statement 1 is optional and can be omited:

var i=2, len=cars.length;
for (; i < len; i++) { 
  document.write(cars[i] + "</br>");
}

You can initiate many values in statement 1 (separated by a comma):

for (i = 0, len = cars.length, text = ""; i < len; i++) { 
  text += cars[i] + "</br>";
}
Statement 1 (optional)

  1. is executed (one time) before the loop (the code block) starts.
  2. sets/initializes a variable before the loop starts (e.g., i = 0).
If you omit statement 2, you must provide a break inside the loop.
Otherwise the loop will never end.

for (i = 0; ; i++)   {
  if (i == 3)  {
    break;
    }
  x = x + "The number is " + i + "</br>";
  }
Statement 2 (optional)

  1. defines the condition for the loop (the code block) to run.
  2. If statement 2 returns true, the loop will start over again,
    if it returns false, the loop will end.
  3. Statement 2 is optional.
You can omit statement 3 and increment values inside the loop instead:

var i = 0, len = cars.length;
for (; i < len; ) { 
  document.write(cars[i] + "</br>");
i++;
}
Statement 3 (optional)

  1. is executed (every time) after the loop (the code block) has been executed.
  2. Statement 3 usually increments a value (i++) of the initial variable
    each time the code block in the loop has been executed.
  3. Statement 3 is optional.

For/in statement loops through the properties of an object.

var person = {fname:"John", lname:"Doe",  age:25}; 
var txt="";
var x;
for (var x in person)   {
  txt += person[x]  //  txt = txt + person[x];
}
// JohnDoe25

Example Explanation
var fruits, text;

fruits = ["Banana", "Orange", "Apple", "Mango"];
text = "<ul>";

fruits.forEach(myFunction);
text += "</ul>";

function myFunction(value) {
  text += "<li>" + value + "</li>";
}
var txt = "";
var numbers = [45, 4, 9, 16, 25];

numbers.forEach(myFunction);

document.getElementById("demo").innerHTML = txt;

function myFunction(value) {
  txt = txt + value + "<br>"; 
}
array.forEach()

calls a callback function
once for each array element.

The function takes 3 arguments:

  1. The current array item value
  2. The item index (optional)
  3. The array itself (all values of array, comma separated, optional)

Read more >>>

Syntax:

while (condition)   {
  code block to be executed
  }
  1. While Loop
    executes a block of statements
    as long as a specified condition is true.
  2. If you forget to increase the variable used in the condition,
    the loop will never end.
    This will crash your browser.
  3. While loop is much the same as a for loop,
    with statement 1 and statement 3 omitted

    for (; i < 5; ) { 
      document.write("The number is " + i + "</br>");
      i++;
    }
    
    while (i < 5) { 
      document.write("The number is " + i + "</br>");
      i++;
    }
    

Syntax:

do  {
  code block to be executed
}
while (condition);
  1. Do/While Loop is a variant of the while loop.
  2. This loop will execute the code block once,
    before checking if the condition is true,
    then it will repeat the loop
    as long as the condition is true.
  3. Do not forget to increase the variable used in the condition, otherwise the loop will never end!
var x = "", i = 0;
do {
  x = x + "The number is " + i + "<br>";
  i++;
}
while (i < 5)  
document.getElementById("demo").innerHTML= x;

JavaScript Data Types

JavaScript has dynamic types.
This means that the same variable can be used to hold different data types

var x; // x is undefined
x = 5; // x is a Number
x = "John"; // x is a String

All JavaScript data types have a valueOf() and a toString() method.

A primitive data value
is a single simple data value
with no additional properties and methods.

The typeof operator can return one of these primitive types:

  1. string
  2. number
  3. boolean
  4. undefined

The typeof operator can return one of these two complex data types:

  1. function
  2. object

The typeof operator returns object for:

  1. objects
  2. arrays
  3. date
  4. null

The typeof operator does not return object for functions.

  1. string
  2. number
  3. boolean
  4. object
  5. function

  1. Object
  2. Date
  3. Array
  4. String
  5. Number
  6. Boolean

String Data Type

JavaScript Strings
any text(zero or more characters)
inside single or double quotes.

'text'
"text"

Combination of double and single quotes

You can use quotes inside a string,
as long as they don't match the quotes surrounding the string

const answer="It's alright";
const answer="He is called 'Johnny'";
const answer='He is called "Johnny"';

Escape characters

The backslash (\) escape character turns special characters into string characters:

const x = "We are the so-called \"Vikings\" from the north.";

String indexes

String indexes are zero-based,
which means the first character is [0], the second is [1], and so on.

var x = "John";
var y = new String("John");
typeof(x) // returns String
typeof(y) // returns Object

It is a bad practice to define strings as objects.
It slows down execution speed.
The new keyword complicates the code.
This can produce some unexpected results

var x = "John";              
var y = new String("John");
// (x == y) is true because x and y have equal values
(x === y) // is false because x is a string and y is an object.

var x = new String("John");             
var y = new String("John");
// (x == y) is false because x and y are different objects

String.valueOf()
returns the primitive value of a String object
as a string data type.

This value is equivalent to String.prototype.toString().

This method is usually called internally by JavaScript and not explicitly in code.

Example:

const stringObj = new String('foo');

console.log(stringObj);
// expected output: String { "foo" }

console.log(stringObj.valueOf());
// expected output: "foo"

Example:

var x = new String('Hello world');

console.log(x.valueOf()); 
// Displays 'Hello world'

Read more >>>

An empty string value has nothing to do with undefined.

An empty string has both a legal value and a type.

var car = "";    // The value is "",  the typeof is "string"

Template strings in ES6
are string literals allowing embedded expressions.

They were called "template strings" in prior editions of the ES2015 specification.

`string text ${expression} string text`

You can use

  1. multi-line strings,
  2. string interpolation
  3. and expression interpolation

features with them.

Placeholders

${expression}

Placeholders are indicated by the dollar sign and curly braces (${expression}).

The expression gets passed to a function.
The default function just concatenates the parts into a single string.

let x = `Bond`
let bondLn = `My name is ${x}, James ${x}`;
console.log(bondLn);
let one = 1;
let two = 2;
let sum = `Adding ${one} and ${two} gives me ${one + two} `;
let sum2 = `one + two = ${one + two}  not 4`; // one + two = 3 not 4

String Interpolation

`string ${variable}`
allows you to inject variables directly into a string.

function crazyString(something, someone, somewhere) {
  return someone + " was looking for " + something + " in the general vicinity of " + somewhere;
}

function organizedString(something, someone, somewhere) {
  return `${someone} was looking for ${something} in the general vicinity of ${somewhere}`;
}

Escape characters

  1. No need to add \n for new lines
  2. No need to escape quotes or special characters (+, =, /)
  3. To escape a back-tick in a template literal,
    put a backslash \ before the back-tick.
`string text line 1  // "string text line 1
 string text line 2`  // string text line 2"

Nesting templates

allow inner backticks
simply by using them inside a placeholder ${ }
within the template.

Tagged template

If there is an expression preceding the template literal (tag here),
this is called a "tagged template".

In that case, the tag expression (usually a function)
gets called with the template literal,
which you can then manipulate before outputting.

tag `string text ${expression} string text` //tagged template

JavaScript, methods and properties are also available to primitive values,
because JavaScript treats primitive values as objects
when executing methods and properties.

String Properties

Example Explanation
const str = "Hello World!";

console.log(str.length);
// 12
str.length

returns the number of characters in a string

function employee(name, jobtitle, born) {
  this.name = name;
  this.jobtitle = jobtitle;
  this.born = born;
}
employee.prototype.salary = 2000;

const fred = new employee(
  "Fred Flintstone", "Caveman", 1970
);
console.log(fred.salary)
// 2000
str.prototype

Syntax: object.prototype.name = value

allows to add
new properties and methods
to existing object types.

Prototype is a global property
available with almost all JavaScript objects.

const str = "Hello World!";

console.log(str.constructor);
function String() { [native code] }
// 
str.constructor
returns the string's constructor function

String Methods

All string methods return a new string.
They don't modify the original string.

Formally said: Strings are immutable:
Strings cannot be changed, only replaced.

Converting to Upper and Lower Case

Method Example Explanation
toLowerCase()
var text1 = "Hello World!";

var text2 = text1.toLowerCase(); 
// text2 is text1 converted to lower
converts a string to lower case
toUpperCase()
var text1 = "Hello World!";
 
var text2 = text1.toUpperCase();  
// text2 is text1 converted to upper
converts a string to upper case

Method Example Explanation
concat()
var text1 = "Hello";
var text2 = "World";

var text3 = text1.concat(" ", text2);

var text = "Hello".concat(" ", "World!");
// Hello World!
joins two or more strings
The + Operator
var text1 = "Hello";
var text2 = "World";

text3 = text1 + text2;

var text = "Hello" + " " + "World!";
// Hello World!
joins two or more strings

Remove whitespace: trim()

Method Example Explanation
trim()
var str = "       Hello World!        ";

alert(str.trim());
// Hello World!
removes whitespace from both sides of a string

Method Example Explanation
split(“separator”)
var txt = "a,b,c,d,e";
txt.split(","); // a,b,c,d,e,f  Split on commas
txt.split(" "); // Split on spaces
txt.split("|"); // Split on pipe
If the separator is omitted,
the returned array will contain
the whole string in index [0].

If the separator is "",
the returned array will be an array of single characters

...spread operator Function calls:

myFunction(...iterableObj);

For array literals or strings:

[...iterableObj, '4', 'five', 6];
// …iterableOb  = [argument1, argument2, argument3]

For object literals (since ECMAScript 2018):

let objClone = { ...obj };

Example:

let one = 1;
let two = 2;

let tagged = function(strArray, ...vals) {
  console.log(strArray);
  console.log(vals)
}

tagged`adding${one} and ${two} gives me ${one + two}`;

Example:

var parts = ['shoulders', 'knees']; 

var lyrics = ['head', ...parts, 'and', 'toes']; 
// ["head", "shoulders", "knees", "and", "toes"]

Example:

function sum(x, y, z) {
  return x + y + z;
}

const numbers = [1, 2, 3];

console.log(sum(...numbers));
// expected output: 6

console.log(sum.apply(null, numbers));
// expected output: 6
Converts to an array

Spread syntax allows

  1. an iterable
    such as an array expression or string
    to be expanded in places
    where zero or more
    arguments (for function calls)
    or elements (for array literals)
    are expected,
  2. or an object expression to be expanded
    in places where
    zero or more key-value pairs (for object literals)
    are expected.

String.fromCharCode()

Example Explanation
console.log(String.fromCharCode(189, 43, 190, 61));
// expected output: "½+¾="

String.fromCharCode(65, 66, 67);   
// returns "ABC"

String.fromCharCode(0x2014);       
// returns "—"

String.fromCharCode(0x12014);      
// also returns "—"; 
// the digit 1 is truncated and ignored

String.fromCharCode(8212);         
// also returns "—"; 
// 8212 is the decimal form of 0x2014
String.fromCharCode(num1[, ...[, numN]])

returns a string
created from the specified sequence
of UTF-16 code units

num1, ..., numN
The range is between 0 and 65535 (0xFFFF).
Numbers greater than 0xFFFF are truncated.
No validity checks are performed.

Read more >>>

Extracting String Characters: charAt(position), charCodeAt(position), Property access [ ]

Method Example Explanation
charAt()
var str = "HELLO WORLD";

str.charAt(0);  // returns H
returns the character at a specified index (position) in a string
charCodeAt()
var str = "HELLO WORLD";

str.charCodeAt(0); // returns 72
returns the UTF-16 unicode
(an integer between 0 and 65535)
of the character
at a specified index in a string
Property access [ ]
var str = "HELLO WORLD";

str[0] = "A"; // Gives no error, but does not work
str[0]; // returns H
ECMAScript 5 (2009) allows property access [ ] on strings

Property access might be a little unpredictable:

  1. It does not work in Internet Explorer 7 or earlier
  2. It makes strings look like arrays
    (but they are not)
  3. If no character is found, [ ] returns undefined,
    while charAt() returns an empty string.
  4. It is read only.
    str[0] = "A" gives no error (but does not work!)

If you want to work with a string as an array, you can convert it to an array.

Extracting String Parts

These methods extract a part of a string
and return the extracted part in a new string.

JavaScript counts positions from zero.
First position is 0.

Method Example Explanation
slice(start, end)
var str = "Apple, Banana, Kiwi";

var res = str.slice(7, 13); //Banana

var res = str.slice(-12, -6); //Banana

var res = str.slice(7); // Banana, Kiwi

var res = str.slice(-12); // Banana, Kiwi
takes 2 parameters:

  1. the start position,
  2. and the end position (end not included).

If a parameter is negative,
the position is counted from the end of the string.

If the second parameter is omitted,
the method will slice out the rest of the string.

substring(start, end)
var str = "Apple, Banana, Kiwi";
var res = str.substring(7, 13); //Banana
substring() is similar to slice().

The difference is that
substring() cannot accept negative indexes.

substr(start, length)
var str = "Apple, Banana, Kiwi";
var res = str.substr(7, 6); // Banana
substr() is similar to slice().

The difference is that
the second parameter specifies the length of the extracted part.

Finding a String in a String

Numeric value of position of found text within string.
JavaScript counts positions from zero.

Method Example Explanation
indexOf(“string”, startingPosition )
var str = "Please locate where 'locate' occurs!";
var pos = str.indexOf("locate", 15); // 21
Returns the index (position)
of the first occurrence of a specified text in a string
returns -1 if the text is not found

cannot take powerful search values
(regular expressions).

lastIndexOf()
var str = "Please locate where 'locate' occurs!";
var pos = str.lastIndexOf("locate", 15); // 7
returns the index of
the last occurrence of a specified text in a string

searches backwards,
search starts at position counting from the end

return -1 if the text is not found

search(“string”)
var str = "Please locate where 'locate' occurs!";
var pos = str.search("locate");

case-insensitive search for "yuwebdesign" in a string:

var str = "Visit yuwebdesign";
var n = str.search(/yuwebdesign/i); // 6
searches a string for
a first occurrence of a specified text
and returns the position of the match.

Can use regular expression to search for a match.

The search() method cannot take a second start position argument.

A regular expression
is a sequence of characters that forms a search pattern.

A regular expression can be
a single character,
or a more complicated pattern.

Regular expressions
can be used to perform all types of
text search and text replace operations.

Syntax:

/pattern/modifiers

pattern will be searched, no quotes
modifier modifies the search

Regular Expression Modifiers

Modifier Example Explanation
/pattern/i
var str = "Visit yuwebdesign";
var n = str.search(/yuwebdesign/i); // 6
case-insensitive matching
/pattern/g global match - replace all matches
/pattern/m multiline matching

Regular Expression Patterns

Brackets are used to find a range of characters.

Pattern Example Explanation
[abc] Global search for the character "h" in a string:

var patt1 = /[h]/g;
Find any of the characters between the brackets
[0-9] Global search for the numbers 1 to 4:

var patt1 = /[1-4]/g;
Find any of the digits between the brackets
(x|y) Global search for any of the specified alternatives (red|green):

function myFunction() {
  var str = "re, green, red, green, gren, gr, blue, yellow";
  var patt1 = /(red|green)/g;
  var result = str.match(patt1);
  document.getElementById("demo").innerHTML = result;
}  // green,red,green
Find any of the alternatives separated with |

Regular Expression Metacharacters

Metacharacters
are characters with a special meaning.

Metacharacters Example Explanation
\d
function myFunction() {  // global search for digits in a string
  var str = "Give 100%!"; 
  var patt1 = /\d/g;
  var result = str.match(patt1);
  document.getElementById("demo").innerHTML = result;
}  // 1,0,0
Find a digit
\s Global search for whitespace characters:

function myFunction() {  
  var str = "Is this all there is?";
  var patt1 = /\s/g;
  var result = str.match(patt1);
  document.getElementById("demo").innerHTML = result;
}  // , , ,

Find a whitespace character
\b Global search for "W3" at the beginning or end of a word in a string

function myFunction() {
  var str = "Visit W3Schools"; 
  var patt1 = /\bW3/g;
  var result = str.match(patt1);
  document.getElementById("demo").innerHTML = result;
}  // W3
Find a match at the beginning or at the end of a word
\uxxxx Global search for the hexadecimal number 0057 (W) in a string

function myFunction() {
  var str = "Visit W3Schools. Hello World!"; 
  var patt1 = /\u0057/g;
  var result = str.match(patt1);
  document.getElementById("demo").innerHTML = result;
}  // W,W
Find the Unicode character
specified by the hexadecimal number xxxx

Regular Expression Quantifiers

Quantifiers define quantities

Metacharacters Example Explanation
n+ Matches any string
that contains at least one n
n* Matches any string
that contains zero or more occurrences of n
n? Matches any string
that contains zero or one occurrences of n

Regular Expression Object Methods

RegExp Method Example Explanation
test()
var patt = /e/;
patt.test("The best things in life are free!");  // true

You don't have to put the regular expression in a variable first:

/e/.test("The best things in life are free!");  // true
searches a string for a pattern,

returns boolean (true or false),
depending on the result.

exec() Search a string for the character "e":

var obj = /e/.exec("The best things in life are free!");
document.getElementById("demo").innerHTML =
"Found " + obj[0] + " in position " 
+ obj.index + " in the text: " + obj.input;

// Found e in position 2 in the text: 
// The best things in life are free!
searches a string for a specified pattern,

returns the found text as an object.

If no match is found, it returns an empty (null) object.

str.match(regexp)
const paragraph = 'The quick brown fox' 
+'jumps over the lazy dog. It barked.';

const regex = /[A-Z]/g;
const found = paragraph.match(regex);

console.log(found);
// returns: Array ["T", "I"]
const str = 'For more information, see Chapter 3.4.5.1';
const re = /see (chapter \d+(\.\d)*)/i;
const found = str.match(re);

console.log(found);

// returns [ 'see Chapter 3.4.5.1',
//        'Chapter 3.4.5.1',
//        '.1',
//        index: 22,
//        input: 'For more information, see Chapter 3.4.5.1' ]

// 'see Chapter 3.4.5.1' 
// is the whole match.

// 'Chapter 3.4.5.1' 
// was captured by '(chapter \d+(\.\d)*)'.

// '.1' 
// was the last value captured by '(\.\d)'.

// The 'index' property (22) 
// is the zero-based index of the whole match.

// The 'input' property 
// is the original string that was parsed.
const str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
+'abcdefghijklmnopqrstuvwxyz';
const regexp = /[A-E]/gi;
const matches_array = str.match(regexp);

console.log(matches_array);
// ['A', 'B', 'C', 'D', 'E', 'a', 'b', 'c', 'd', 'e']
retrieves the result
of matching a string
against a regular expression.

Returns an array of matches
whose contents depend
on the presence or absence of the global (g) flag,
or null if no matches are found.

If the regular expression does not include the g flag,
str.match() will return the same result as RegExp.exec().

If regexp is a non-RegExp object,
it is implicitly converted to a RegExp
by using new RegExp(regexp).

If you don't give any parameter
and use the match() method directly,
you will get an Array with an empty string: [""].

Read more >>>

When to use each method

  1. If you need to know
    if a string matches a regular expression RegExp,
    use RegExp.test().
  2. If you only want the first match found,
    you might want to use RegExp.exec() instead.
  3. If you want to obtain capture groups
    and the global flag is set,
    you need to use RegExp.exec()
    or String.prototype.matchAll() instead.

localeCompare()

Example Explanation
referenceStr.localeCompare(
  compareString[, locales[, options]]
)

'a'.localeCompare('c'); 
// -2 or -1 (or some other negative value)
// Alphabetically letter "a" is before "c" 

'check'.localeCompare('against'); 
// 2 or 1 (or some other positive value)
// Alphabetically the word "check" 
//comes after "against" 

'a'.localeCompare('a'); 
// 0
// "a" and "a" are equivalent

locales

console.log('ä'.localeCompare('z', 'de')); 
// a negative value
// in German, ä sorts before z

console.log('ä'.localeCompare('z', 'sv')); 
// a positive value
// in Swedish, ä sorts after z

options:

// in German, ä has a as the base letter
console.log('ä'.localeCompare(
   'a', 'de', { sensitivity: 'base' }
)); 
// 0
// in German, 
// ä has a as the base letter

console.log('ä'.localeCompare(
   'a', 'sv', { sensitivity: 'base' }
)); 
// a positive value
// in Swedish, 
// ä and a are separate base letters
compareString is compared against referenceStr

returns a number
indicating whether a reference string comes

  1. before (returns negative number)
  2. after (returns positive number)
  3. or is the same as (returns 0 if equivalent)

the given string (compareString) in sort order.

Warning:
Do not rely on exact return values of -1 or 1!
W3C specification only mandates negative and positive values.
Some browsers may return -2 or 2 or other values.

locales and options arguments
specify the language
whose sort order and formatting conventions to use
and customize the behavior of the function.

locales:
results vary between languages.
to get the sort order of the language
used in the user interface of your application,
make sure to specify that language
(and possibly some fallback languages)
using the locales argument

Sorting with localeCompare

Sort an array
case-insensitive sorting for an array

let items = ['réservé', 'Premier', 'Cliché', 'communiqué', 'café', 'Adieu'];

items.sort( (a, b) => a.localeCompare(b, 'fr', {ignorePunctuation: true})); 
// ['Adieu', 'café', 'Cliché', 'communiqué', 'Premier', 'réservé']

Numeric sorting

console.log("2".localeCompare("10")); 
// 1
// by default, "2" > "10"

numeric using options:

console.log("2".localeCompare("10", undefined, {numeric: true})); 
// -1

numeric using locales tag:

console.log("2".localeCompare("10", "en-u-kn-true")); 
// -1

Read more >>>

replace()

Example Explanation
replace()

str = "Please visit Disneyland!";
var n = str.replace("Disneyland", "Me");
// Please visit Me!

str = "Please visit Disneyland!";
var n = str.replace(/DISNEYLAND/i, "Me");
// Please visit Me!

str = "Please visit Disneyland and Disneyland!";
var n = str.replace(/Disneyland/g, "Me");
// Please visit Me and Me!
replaces a specified value with another value in a string

returns a modified string
where the pattern is replaced.

Can take regular expressions.

does not change the string it is called on, returns a new string.

By default, replaces only the first match.
To replace all matches, use a regular expression with a /g flag (global match).

By default, case sensitive.
Use a regular expression with an /i flag (insensitive) for case insensitive.

Boolean Data Type

Booleans are often used in conditional testing
and only have two values: true or false.

var x = true;
var y = false;

Normally JavaScript booleans are primitive values created from literals:

var x = false;

But booleans can also be defined as objects with the keyword new:

var myBoolean = new Boolean();

The Boolean object is used to convert a non-Boolean value to a Boolean value (true or false).

If the Boolean object has no initial value, or if the passed value is one of the following:

  1. 0
  2. -0
  3. null
  4. ""
  5. false
  6. undefined
  7. NaN

the object is set to false.
For any other value it is set to true (even with the string "false")!

Do not create Boolean objects.
It slows down execution speed.
The new keyword complicates the code.
This can produce some unexpected results:

var x = false;  // typeof x returns boolean
var y = new Boolean(false);  // typeof y returns object
// (x == y) is true because x and y have equal values
// (x === y) is false because x and y have different types

var x = new Boolean(false);             
var y = new Boolean(false);
// (x == y) is false because objects cannot be compared

The Boolean() Function
checks if an expression (or a variable) is true.

Everything With a "Value" is True

  1. Any (not empty) string is true
  2. Even the string 'false' is true
  3. Any expression (except zero) is true
Boolean(10 > 9)        // returns true
(10 > 9)              // also returns true
10 > 9                // also returns true
Boolean('false'); // true

Everything Without a "Value" is False

  1. The Boolean value of 0 (zero) is false
  2. The Boolean value of -0 (minus zero) is false
  3. Boolean value of "" (empty string) is false
  4. The Boolean value of undefined is false
  5. The Boolean value of null is false
  6. The Boolean value of false is false
  7. The Boolean value of NaN is false
Boolean(0);       // returns false
Boolean(-0);      // returns false
Boolean(“”);       // returns false

var x;
Boolean(x);       // returns false

var x = null;
Boolean(x);       // returns false

var x = false;
Boolean(x);       // returns false

var x = 10 / "H";
Boolean(x);       // returns false

Number Data Type

JavaScript Numbers
are 64-bit Floating Point

  1. JavaScript is not a typed language.
    Unlike many other programming languages,
    it does not define different types of numbers, like

    1. integers,
    2. short,
    3. long,
    4. floating-point etc.

    JavaScript has only one type of numbers.

  2. Numbers can be written with, or without decimals.
  3. Extra large or extra small numbers
    can be written with scientific (exponential) notation

Example:

var x1=34.00;      
// Written with decimals

var x2=34;         
// Written without decimals

var y=123e5;      
// 12300000

var z=123e-5;     
// 0.00123

Integers
(numbers without a period or exponent notation)
are accurate up to 15 digits:

var x = 999999999999999;   
// x is 999999999999999

var y = 9999999999999999;  
// y is 10000000000000000

Decimals
The maximum number of decimals is 17,
but floating point arithmetic is not always 100% accurate:

var x = 0.2 + 0.1;         
// 0.30000000000000004

Solve this problem by multiplying and dividing

let x = (0.2 * 10 + 0.1 * 10) / 10;       
// 0.3

Hexadecimal
By default, JavaScript displays numbers as base 10 decimals.

Hexadecimal
Hexadecimal is base 16.
JavaScript interprets numeric constants as hexadecimal
if they are preceded by 0x.

Decimal
Never write a number with a leading zero (like 07).
Some JavaScript versions interpret numbers as octal
if they are written with a leading zero.

Decimal
Octal is base 8.

Binary
Binary is base 2

You can use the toString() method
to output numbers from base 2 to base 36:

let x = 0xFF;        
// x will be 255

let myNumber = 32;

myNumber.toString(10);  
// returns 32

myNumber.toString(32);  
// returns 10

myNumber.toString(16);  
// returns 20

myNumber.toString(8);   
// returns 40

myNumber.toString(2);   
// returns 100000

Normally JavaScript numbers are primitive values created from literals.

But numbers can also be defined as objects with the keyword new:

let x = 123;
let y = new Number(123);

typeof(x) // returns Number
typeof(y) // returns Object

Do not create Number objects.
It slows down execution speed.
The new keyword complicates the code.
This can produce some unexpected results:

var x = 123;              
var y = new Number(123);
(x == y) // true because x and y have equal values
(x === y) // false because x is a number and y is an object.

var x = new Number(500);             
var y = new Number(500);
(x == y) // false because objects cannot be compared

  1. All number properties
    are properties of JavaScripts' number object wrapper
    called Number.
  2. These properties can only be accessed as Number.MAX_VALUE.
  3. Using myNumber.MAX_VALUE,
    where myNumber is a variable, expression, or value,
    will return undefined:

    var x = 6;
    var y = x.MAX_VALUE;    // y becomes undefined
    

Number Properties

Example Description
Number.MAX_SAFE_INTEGER
// 9007199254740991
Number.MAX_SAFE_INTEGER

Returns the largest safe integer possible in JavaScript

var x = Number.MAX_VALUE 
// 1.7976931348623157e+308
Number.MAX_VALUE

Returns the largest number possible in JavaScript

var x = Number.MIN_VALUE; 
// 5e-324
Number.MIN_VALUE

Returns the smallest number possible in JavaScript

var x = Number.POSITIVE_INFINITY;  
// Infinity

var x = 1 / 0;  
// Infinity
Number.POSITIVE_INFINITY
Represents infinity (returned on overflow)
var x = Number.NEGATIVE_INFINITY;  // -Infinity
var x = -1 / 0;  // -Infinity
Number.NEGATIVE_INFINITY
Represents negative infinity (returned on overflow)
var x = Number.NaN;  
// NaN

var x = 100 / "Apple";  
// x will be NaN (Not a Number)
Number.NaN

Represents a "Not-a-Number" value

NaN is a JavaScript reserved word
indicating that a number is not a legal number.

Trying to do arithmetic
with a non-numeric string
will result in NaN (Not a Number).

Number Methods

All number methods
can be used on any type of numbers
(literals, variables, or expressions)

  1. toExponential()
  2. toFixed()
  3. toPrecision()
  4. valueOf()

Example Description
var x = 9.656;

x.toExponential(2);     
// returns 9.66e+0

x.toExponential(4);     
// returns 9.6560e+0

x.toExponential(6);     
// returns 9.656000e+0
toExponential()

Returns a string,
with a number rounded
and written using exponential notation.

A parameter defines
the number of characters
behind the decimal point.

The parameter is optional.
If you don't specify it,
JavaScript will not round the number.

Example Description
var x = 9.656;

x.toFixed(0);           
// returns 10

x.toFixed(2);           
// returns 9.66

x.toFixed(4);           
// returns 9.6560

x.toFixed(6);           
// returns 9.656000
toFixed()

Returns a string, with the number written with a specified number of decimals.

toFixed(2) is perfect for working with money.

Example Description
var x = 9.656;

x.toPrecision();        
// returns 9.656

x.toPrecision(2);       
// returns 9.7

x.toPrecision(4);       
// returns 9.656

x.toPrecision(6);       
// returns 9.65600
toPrecision()

returns a string,
with a number written with a specified length

Example Description
var x = 123;

x.valueOf();            
// returns 123 from variable x

(123).valueOf();        
// returns 123 from literal 123

(100 + 23).valueOf();   
// returns 123 from expression 100 + 23
valueOf()

returns a number as a number

In JavaScript, a number can be

  1. a primitive value (typeof = number)
  2. or an object (typeof = object)

The valueOf() method
is used internally in JavaScript
to convert Number objects to primitive values.

There is no reason to use it in your code.

Math Object
allows to perform mathematical tasks.

Math object includes several mathematical constants and methods.

Syntax

var x = Math.PI;
var y = Math.sqrt(16);

No Math Constructor

Unlike other global objects,
the Math object has no constructor.

Methods and properties are static.

All properties and methods of Math
can be called by using Math as an object
without creating it.

Mathematical Constants

Example Explanation

Math.E
returns Euler's number

Math.PI
returns 3.141592653589793

Math.SQRT2
returns the square root of 2

Math.SQRT1_2
returns the square root of 1/2

Math.LN2
returns the natural logarithm of 2

Math.LN10
returns the natural logarithm of 10

Math.LOG2E
returns base 2 logarithm of E

Math.LOG10E
returns base 10 logarithm of E

Mathematical Methods

Example Explanation
Math.min(0, 150, 30, 20, -8, -200);  
// returns -200

document.getElementById("demo").innerHTML=Math.min(5,10);
// Return the lowest number of 5 and 10
Math.min(x, y, z, ..., n)
the lowest value in a list of arguments
Math.max(0, 150, 30, 20, -8, -200);  
// returns 150

document.getElementById("demo").innerHTML=Math.max(5,10)
// Returns  the highest number of 5 and 10
Math.max(x, y, z, ..., n)
the highest value in a list of arguments
document.write(Math.random()); 
// returns a random number

Math.random() + Math.floor()

document.write(Math.floor(Math.random()*10));
// returns a random integer from 0 to 9

Math.floor(Math.random() * 11);      
// returns a random integer from 0 to 10

Math.floor(Math.random() * 10) + 1;  
// returns a random integer from 1 to 10

random number between min and max

function getRndInteger(min, max) {
  return Math.floor(Math.random() * (max - min)) + min;
}
// random number between 
// min (included) and max (excluded)

function getRndInteger(min, max) {
  return Math.floor(Math.random() * (max - min + 1) ) + min;
}
// random number between 
// min and max (both included)
Math.random()
random number between
0 (inclusive) and 1(exclusive).

always returns a number lower than 1

Math.random() used with Math.floor()
is used to return random integers.

document.write(Math.round(4.7)); 
// returns 5

Math.round(4.4);    
// returns 4
Math.round(x)
round x to the nearest integer
Math.ceil(x)
value of x rounded up to its nearest integer
Math.floor(4.7);    
// returns 4
Math.floor(x)
value of x rounded down to its nearest integer
Math.pow(8, 2);      
// returns 64
Math.pow(x, y)
value of x to the power of y
Math.sqrt(64);      
// returns 8
Math.sqrt(x)
square root of x

Math.exp(x)
Returns the value of Ex

Math.log(x)
Returns the natural logarithm (base E) of x
Math.abs(-4.7);     
// returns 4.7
Math.abs(x)
absolute (positive) value of x
Math.sin(90 * Math.PI / 180);     
// returns 1 (the sine of 90 degrees)
Math.sin(x)
sine (between -1 and 1) of the angle x (in radians)

If you want to use degrees instead of radians,
you have to convert degrees to radians:

angle in radians = angle in degrees x PI / 180.

Math.cos(0 * Math.PI / 180);     
// returns 1 (the cos of 0 degrees)
Math.cos(x)
cosine (between -1 and 1) of the angle x (in radians)

Math.tan(x)
returns the tangent of an angle

Math.acos(x)
returns the arccosine of x, in radians

Math.asin(x)
returns the arcsine of x, in radians

Math.atan(x)
arctangent of x as a numeric value
between -PI/2 and PI/2 radians

Math. atan2(y, x)
arctangent of the quotient of its arguments

Infinity
the value JavaScript will return
if you calculate a number outside the largest possible number.

Division by 0 (zero) also generates Infinity.

Infinity is a number: typeof Infinity returns number.

Infinity - 1 === Infinity 
// true

let x =  2 / 0;       
// x will be Infinity

let y = -2 / 0;       
// y will be -Infinity

let myNumber = 2;
while (myNumber != Infinity) {   
  // Execute until Infinity
  myNumber = myNumber * myNumber;
}

NaN (Not a number)
is a numeric data type value
representing an undefined or unrepresentable value.

JavaScript reserved word indicating that a number is not a legal number

NaN is a number: typeof NaN returns number.

Trying to do arithmetic with a non-numeric string
will result in NaN

If you use NaN in a mathematical operation,
the result will also be NaN.
Or the result might be a concatenation

0 / 0 
// Nan

Infinity - Infinity 
//Nan

'one' / 'two' 
//Nan

let x = 100 / "Apple";  
// x will be NaN

let x = NaN;
let y = 5;
let z = x + y;         
// z will be NaN

let x = NaN;
let y = "5";
letz = x + y;         
// z will be NaN

Undefined and Null

Undefined

Undefined is the value of a variable with no value,
value is not set.

This is not the same as “not defined” error, where variable (not value) is not set up.

Variable without a value assigned to it is by default undefined:

var car;    // Value is undefined, type is undefined

Any variable can be emptied, by setting the value to undefined.
The type will also be undefined.

car = undefined; // Emptied: value is undefined, type is undefined

Null

Null is used with objects.
It is a good practice to return null for an object that is not defined.

cars=null;
person=null;

In JavaScript null is "nothing".
It is supposed to be something that doesn't exist.

Unfortunately, in JavaScript, the data type of null is an object.
It is a famous bug in JavaScript that typeof null is an object.
It should be null.

Null vs. Undefined

Undefined and null are equal in value but different in type.

typeof undefined // undefined
typeof null // object
null === undefined // false
null == undefined // true

Variables can be emptied by setting the value to null.

var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};
person = null;    // Now value is null, but type is still an object

You can also empty an object by setting it to undefined.

var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};
person = undefined;   // Now both value and type is undefined

Array Data Type

An Array
stores multiple values in one single variable.

Creating an Array

Array Literal

Using an array literal
is the easiest way to create a JavaScript Array

  1. written with square brackets,
  2. separated by commas,
  3. no comma after last element
    Putting a comma after the last element (like "BMW",)
    is inconsistent across browsers.
    IE 8 and earlier will fail.
  4. Spaces and line breaks are not important.
    A declaration can span multiple lines.
  5. semicolon at the end

Syntax

const array_name = [item1, item2, ...];

Example

var cars = ["Saab","Volvo","BMW"];
Using the JavaScript Keyword new

For simplicity, readability and execution speed, use the array literal method.

No need to use the JavaScript's built-in array constructor new Array().
The new keyword only complicates the code.
It can also produce some unexpected results:

const points = new Array(40);  
// Creates an array with 40 undefined elements !!!!!

Regular Array

const cars = new Array();
cars[0] = "Saab";
cars[1]= "Volvo";
cars[2] = "BMW";

Condensed Array

const cars = new Array("Saab","Volvo","BMW");

Indexed Arrays

JavaScript Arrays are Indexed Arrays.

Array indexes are zero-based: the first item is [0].

Access the Elements of an Array

You can access the element values by referring to an index number:

var cars = ["Saab", "Volvo", "BMW"];
document.getElementById("demo").innerHTML = cars[0];
// Saab

cars[0]="Opel";
// modify the first element in cars
document.getElementById("demo").innerHTML = cars;
// Opel, Volvo, BMW

fruits = ["Banana", "Orange", "Apple", "Mango"];
var last = fruits[fruits.length - 1];  
// access the last array element

Associative Arrays (or hashes)

JavaScript does not support arrays with named indexes.

In JavaScript, arrays always use numbered indexes.

If you use named indexes,
JavaScript will redefine the array to a standard object.

After that, some array methods and properties
will produce incorrect results:

const person = [];
person["firstName"] = "John";
person["lastName"] = "Doe";
person["age"] = 46;

const x = person.length;     
// returns 0

const y = person[0];         
// returs undefined

Arrays use numbered indexes.
Objects use named indexes.

JavaScript does not support associative arrays.
You should use objects when you want the element names to be strings (text).
You should use arrays when you want the element names to be numbers.

Arrays are Objects

Arrays are a special kind of objects, with numbered indexes.
The typeof operator in JavaScript returns "object" for arrays.

The real strength of JavaScript arrays are the built-in predefined properties and methods.

Example Explanation
var fruits = ["Banana", "Orange", "Apple", "Mango"];

fruits.length;   
// the length of fruits is 4
arrayName.length

returns the length of an array (the number of array elements).

is always one more than the highest array index.

var y=myCars.indexOf("Volvo")   // the index position of "Volvo"
arrayName.indexOf

<button onclick="myFunction()">Try it</button>

<script>
Array.prototype.myUcase=function(){
  for (i = 0; i < this.length; i++){
    this[i]=this[i].toUpperCase();
  }
}

function myFunction(){
  var fruits = ["Banana", "Orange", "Apple", "Mango"];

  fruits.myUcase();

  var x = document.getElementById("demo");
  x.innerHTML = fruits;
}
</script>
Array.prototype.arrayName

creates new methods

Prototype is a global constructor in JavaScript. It can construct new properties and methods for any JavaScript Objects


Array iteration methods
operate on every array item.

  1. for loop
  2. forEach()
  3. Array.map()
  4. Array.filter()
  5. Array.reduce()
  6. Array.reduceRight()
  7. Array.every()
  8. Array.some()
  9. Array.indexOf()
  10. Array.lastIndexOf()
  11. Array.find()
  12. Array.findIndex()


Example Explanation
var fruits = ["Banana", "Orange", "Apple", "Mango"];

fruits.push("Lemon");  
// Banana,Orange,Apple,Mango,Lemon

var x = fruits.push("Kiwi");   
//  the value of x is 6
push()

adds a new element to the end of an array,

returns the new array length

const fruits = ["Banana", "Orange", "Apple", "Mango"];

fruits[fruits.length] = "Lemon";  
// Banana,Orange,Apple,Mango,Lemon

Example of creating undefned elements:

const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits[6] = "Lemon";
// Banana, Orange, Apple, Mango, undefined, undefined, Lemon

arrayName[arrayName.length]

Adds/appends to the end of an array

Adding elements with indexes higher than array length
can create undefined "holes" in an array

var fruits = ["Banana", "Orange", "Apple", "Mango"];

fruits.unshift("Lemon");    
// adds a new element "Lemon" to fruits

var x = fruits.unshift("Lemon");
//  the value of x is 5
unshift()

adds a new element
to the beginning of an array,
and "unshifts" older elements

returns the new array length

Example Explanation
const fruits = ["Banana", "Orange", "Apple", "Mango"];

fruits.pop();  
// removes the last element ("Mango") from fruits

const x = fruits.pop();      
// the value of x is "Mango"
pop()

removes the last element from an array

returns the value that was "popped out"

const fruits = ["Banana", "Orange", "Apple", "Mango"];

fruits.shift();  
// removes the first element "Banana" from fruits

const x = fruits.shift();    
// the value of x is "Banana"
shift()

removes the first element from an array

returns the string that was "shifted out"

const fruits = ["Banana", "Orange", "Apple", "Mango"];

delete fruits[0];           
// Changes the first element in fruits to undefined
delete

Since JavaScript arrays are objects,
elements can be deleted by using the JavaScript operator delete

Using delete may leave undefined holes in the array.
Use pop() or shift() instead.

Example Explanation
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.splice(2, 0, "Lemon", "Kiwi");
// add elements at position 2
// remove 0 elements
// add elements "Lemon", "Kiwi"
// returns Banana,Orange,Lemon,Kiwi,Apple,Mango

const fruits = ["Banana", "Orange", "Apple", "Mango"];
const removed = fruits.splice(2, 2, "Lemon", "Kiwi");
// Apple,Mango

const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.splice(0, 1);        
// removes the first element of fruits
// no new elements will be added
splice(num1, num2, element1, ... elementn)

adds new items to an array
and removes items

The first parameter (num1)
defines the position
where new elements should be added (spliced in).

The second parameter (num2)
defines how many elements should be removed.

The rest of the parameters (element1, element2, elementn)
define the new elements to be added.

The splice() method returns an array with the deleted items

With clever parameter setting,
you can use splice() to remove elements
without leaving "holes" in the array.

Example Explanation
var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
var citrus = fruits.slice(1, 3); 
// Orange,Lemon

var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
var citrus = fruits.slice(1);  
// starting from element 1 ("Orange")
// Orange,Lemon,Apple,Mango
slice(argument1, argument2)
slices out a piece of an array into a new array.

selects elements from the start argument,
and up to (but not including) the end argument.

If the end argument is omitted, slices out the rest of the array.

creates a new array. It does not remove any elements from the source array.

Example Explanation
const myGirls = ["Cecilie", "Lone"];
const myBoys = ["Emil", "Tobias", "Linus"];
const myChildren = myGirls.concat(myBoys);   
// Concatenates (joins) myGirls and myBoys

const arr1 = ["Cecilie", "Lone"];
const arr2 = ["Emil", "Tobias", "Linus"];
const arr3 = ["Robin", "Morgan"];
const myChildren = arr1.concat(arr2, arr3);   
// Concatenates arr1 with arr2 and arr3

const arr1 = ["Cecilie", "Lone"];
const myChildren = arr1.concat(["Emil", "Tobias", "Linus"]);

concat()
creates a new array by merging (concatenating) existing arrays

does not change the existing arrays.
It always returns a new array.

can take any number of array arguments

can take values as arguments

Example Explanation
const points = [40, 100, 1, 5, 25, 10];
document.getElementById("demo").innerHTML = myArrayMax(points);

function myArrayMax(arr) {
  return Math.max.apply(null, arr);
}  

// The highest number is 100
Math.max.apply

finds the highest number in an array.

Math.max.apply(null, [1, 2, 3])
is equivalent to
Math.max(1, 2, 3)

const points = [40, 100, 1, 5, 25, 10];
document.getElementById("demo").innerHTML = myArrayMin(points);

function myArrayMin(arr) {
  return Math.min.apply(null, arr);
}  

// The lowest number is 1
Math.min.apply

finds the lowest number in an array

Math.min.apply(null, [1, 2, 3])
is equivalent to
Math.min(1, 2, 3)

Example Explanation
const fruits = ["Banana", "Orange", "Apple", "Mango"];

fruits.sort();        
// Apple,Banana,Mango,Orange

ascending order:

var points = [40, 100, 1, 5, 25, 10];  

points.sort(function(a, b){return a - b}); 
// 1,5,10,25,40,100

descending order:

var points = [40, 100, 1, 5, 25, 10];

points.sort(function(a, b){return b - a});  
// 100,40,25,10,5,

random order:

var points = [40, 100, 1, 5, 25, 10]; 

points.sort(function(a, b){return 0.5 - Math.random()});
// 25,5,1,100,40,10

highest/lowest array value:

var points = [40, 100, 1, 5, 25, 10];

points.sort(function(a, b){return a - b});
// now points[0] contains the lowest value “1”
// and points[points.length-1] contains the highest value “100”
arrayName.sort()

sorts an array alphabetically
sorts values as strings

Sorting Numbers
produces incorrect result when sorting numbers as strings: 25>100

Fix this by providing a compare function
The purpose of the compare function
is to define an alternative sort order.

The compare function should return a
negative, zero, or positive value,
depending on the arguments

Highest/Lowest Array Value
There are no built-in functions
for finding the max or min value in an array.

However, after you have sorted an array,
you can use the index
to obtain the highest and lowest values.

Sorting a whole array
is a very inefficient method
if you only want to find the highest (or lowest) value.

Example Explanation

reverse()

reverses the elements in an array
use it to sort an array in descending order

Example Explanation
var numbers1 = [45, 4, 9, 16, 25];
var numbers2 = numbers1.map(myFunction);

document.getElementById("demo").innerHTML = numbers2;

function myFunction(value, index, array) {
  return value * 2; // multiply each element by 2
}  

// 90,8,18,32,50
Array.map()

  1. creates a new array by performing a function on each array element.
  2. does not change the original array.
  3. does not execute the function for array elements without values.

takes 3 arguments:

  1. The item value
  2. The item index
  3. The array itself

When a callback function uses only the value parameter,
the index and array parameters can be omitted

Example Explanation
var numbers = [45, 4, 9, 16, 25];
var over18 = numbers.filter(myFunction);

document.getElementById("demo").innerHTML = over18;

function myFunction(value, index, array) {
  return value > 18;
} 
// 45,25
let ages = [45, 4, 9, 16, 25];

const canDrink = ages.filter(function(age) {
  if(age >= 21) {
    return true;
  }
});

const alsoCanDrink = ages.filter(age => age >=21);

Array.filter()

creates a new array
with array elements that satisfy a certain condition.

function takes 3 arguments:

  1. The item value
  2. The item index
  3. The array itself

If the callback function does not use the index and array parameters, they can be omitted

Example Explanation
const numbers = [45, 4, 9, 16, 25];
const allOver18 = numbers.every(myFunction);

document.getElementById("demo").innerHTML = 
"All over 18 is " + allOver18;

function myFunction(value, index, array) {
  return value < 18;
}  
// All over 18 is false
Array.every()

checks if all array values pass a test.

function takes 3 arguments:

  1. The item value
  2. The item index
  3. The array itself

When a callback function uses the first parameter only (value),
the other parameters can be omitted

Example Explanation
var numbers = [45, 4, 9, 16, 25];
var someOver18 = numbers.some(myFunction);

document.getElementById("demo").innerHTML = 
"Some over 18 is " + someOver18;

function myFunction(value, index, array) {
  return value < 18;
} 
// Some over 18 is true
Array.some()

checks if some array values pass a test.

function takes 3 arguments:

  1. The item value
  2. The item index
  3. The array itself

When a callback function uses the first parameter only (value), the other parameters can be omitted

Syntax

Example Explanation
Array.reduce(function(total, value, index, array),  initial value)

Example:

var numbers = [45, 4, 9, 16, 25];
var sum = numbers.reduce(myFunction);

document.getElementById("demo").innerHTML = 
"The sum is " + sum;

function myFunction(total, value, index, array) {
  return total + value;
}  
// The sum of all numbers in an array is 99

Example:

var numbers = [45, 4, 9, 16, 25];
var sum = numbers.reduce(myFunction, 100);

document.getElementById("demo").innerHTML = 
"The sum is " + sum;

function myFunction(total, value) {
  return total + value;  
}
// The sum is 199
Array.reduce()

  1. runs a function on each array element
    to produce (reduce it to) a single value.
  2. works from left-to-right in the array.
  3. does not reduce the original array.
  4. can accept an initial value

the function takes 4 arguments:

  1. The total (the initial value / previously returned value)
  2. The item value
  3. The item index
  4. The array itself

If the callback function
does not use the index and array parameters,
they can be omitted

const numbers = [45, 4, 9, 16, 25];
const sum = numbers.reduceRight(myFunction);

document.getElementById("demo").innerHTML = 
"The sum is " + sum;

function myFunction(total, value) {
  return total + value;
}  
// The sum is 99
Array.reduceRight()

Example Explanation
const numbers = [4, 9, 16, 25, 29];
const first = numbers.find(myFunction);

document.getElementById("demo").innerHTML = 
"First number over 18 is " + first;

function myFunction(value, index, array) {
  return value > 18;
}  
// First number over 18 is 25
Array.find()
returns the value of the first array element that passes a test function.

function takes 3 arguments:

  1. The item value
  2. The item index
  3. The array itself

Example Explanation
var numbers = [4, 9, 16, 25, 29];
var first = numbers.findIndex(myFunction);

document.getElementById("demo").innerHTML = 
"First number over 18 has index " + first;

function myFunction(value, index, array) {
  return value > 18;
}  
//  First number over 18 has index 3
Array.findIndex()
returns the index of the first array element
that passes a test function.

function takes 3 arguments:

  1. The item value
  2. The item index
  3. The array itself

Example Explanation
const fruits = ["Apple", "Orange", "Apple", "Mango"];
const a = fruits.indexOf("Apple");

document.getElementById("demo").innerHTML = 
"Apple is found in position " + (a + 1);  
// Apple is found in position 1
Array.indexOf(item, start)

searches an array for an element value
and returns its position.

returns -1 if the item is not found.

  1. item - Required.
    The item to search for.
  2. start - Optional.
    Where to start the search.

    Negative values will start
    at the given position
    counting from the end,
    and search to the end.

Example Explanation
const fruits = ["Apple", "Orange", "Apple", "Mango"];
const a = fruits.lastIndexOf("Apple");

document.getElementById("demo").innerHTML = 
"Apple is found in position " + (a + 1);
  
// Apple is found in position 3
Array.lastIndexOf()

searches from the end of the array
for an element value
and returns its position.

Example Explanation
const names = ['John', 'Paul', 'George', 'Ringo', 'John'];

let unique = [...new Set(names)];
console.log(unique); 

// 'John', 'Paul', 'George', 'Ringo'
Set
Set object stores unique values of any type.

In other words, Set will automatically remove duplicates for us.

let x = (names) => 
names.filter((v,i) => names.indexOf(v) === i);

x(names); 
// 'John', 'Paul', 'George', 'Ringo'
filter()

function removeDups(names) {

  let unique = {};
  
  names.forEach(function(i) {
    if(!unique[i]) {
      unique[i] = true;
    }
  });
  
  return Object.keys(unique);
}

removeDups(names); // // 'John', 'Paul', 'George', 'Ringo'
forEach()

let dupesFree = [];

for (let i = 0; i < names.length; i++){
  if(dupesFree.indexOf(names[i] === -1) { // returns -1 if not found
    dupesFree.push(names[i]);
  }
}
for loop

Object Data Type

Example Explanation
const person = {
    firstname: "John", 
    lastname: "Doe", 
    id: 5566
};
person = new Object();
person.firstname = "John";
person.lastname = "Doe";
person.age = 50;
person.eyecolor = "blue";
JavaScript Objects

are variables containers
for named data values
called properties or methods.

But objects can contain many values.

Object definition

You define (and create) a JavaScript object with an object literal.

Spaces and line breaks are not important.
An object definition can span multiple lines.

An object is delimited by curly braces.
Inside the braces
the object's properties
are defined as name and value pairs (name : value).
The properties are separated by commas, semicolon at the end.

var x = new String();        // Declares x as a String object
var x = new Number;
var y = new Boolean;
new keyword

When a JavaScript variable is declared with the keyword "new",
the variable is created as an object.

Avoid String, Number, and Boolean objects.
They complicate your code and slow down execution speed.

car.name = Fiat
car.model = 500
car.weight = 850kg
car.color = white
const message="Hello World!";
const x = message.length;
Object Properties
are values (name:values pairs) associated with objects.
("What object knows").

The properties of the car include
name, model, weight, color, etc.

All cars have these properties,
but the property values differ from car to car.

Accessing Object Properties

  1. objectName.propertyName
    name = person.lastName;
  2. objectName [“propertyName”]
    name = person["lastName"];
car.start()
car.drive()
car.brake()
Object Methods

are actions that objects can perform.
("What object does").

Methods are stored in properties as function definitions.
A method is a function stored as a property.

It is common, in object oriented languages, to use camel-case names.

The methods of the car could be start(), drive(), brake(), etc.
All cars have these methods,
but they are performed at different times.

Accessing Object Methods

objectName.methodName()

name = person.fullName();

Example Explanation
var person = {
  firstName: "John",
  lastName : "Doe",
  id: 5566,
  fullName: function() {
    return this.firstName + " " + this.lastName;
  }
};

// this is the person object that "owns" the fullName function.

// this.firstName means the firstName property of this object.
this keyword
In a function definition,
this refers to the "owner" of the function.

Determine Data Type

typeof
returns the type of a variable or an expression.

The typeof operator can return one of these primitive data types:

  1. string
  2. number
  3. boolean
  4. undefined

The typeof operator can return one of these two complex data types:

  1. function
  2. object

Comparing data of different types may give unexpected results:
you cannot use typeof to determine
if a JavaScript object is

  1. an array
  2. a date
  3. null

It will return object for above cases.

The typeof operator does not return object for functions.

The Data Type of typeof
The typeof operator is not a variable.
It is an operator.
Operators ( + - * / ) do not have any data type.

But, the typeof operator always returns
a string containing the type of the operand.

Example:

typeof 3.14 // Returns "number"
typeof NaN // Returns "number"
typeof (3 + 4)  // 'number'
typeof 0 // 'number'

typeof '0' //'string'
typeof "" // "string"
typeof "John" // "string"

typeof {name:'John', age:34}  // "object"
typeof [1,2,3,4]  // "object"
typeof null // "object"
typeof new Date() //"object"
 
typeof false // "boolean"

typeof function () {} // "function"

typeof myCar // Returns "undefined"

Read more >>>

instanceof
returns true if an object
is an instance
of an object type

Read more >>>

The constructor property
returns the constructor function for all JavaScript variables.

You can check the constructor property to find out if

  1. an object is an Array
    (contains the word "Array")
  2. an object is a Date
    (contains the word "Date")

Example:

"John".constructor  // Returns function String()  {[native code]}
(3.14).constructor // Returns function Number()  {[native code]}
false.constructor // Returns function Boolean() {[native code]}
[1,2,3,4].constructor // Returns function Array()   {[native code]}
{name:'John',age:34}.constructor // Returns function Object()  {[native code]}
new Date().constructor // Returns function Date()    {[native code]}
function () {}.constructor // Returns function Function(){[native code]}

Check if object is array

function isArray(myArray) {
  return myArray.constructor.toString().indexOf("Array") > -1;
}

function isArray(myArray) {
  return myArray.constructor === Array;
}

Check if object is date

function isDate(myDate) {
  return myDate.constructor.toString().indexOf("Date") > -1;
}

function isDate(myDate) {
  return myDate.constructor === Date;
}

You can not check for a Nan with equality operator.
The compiler doesn't know what the value of NaN is.

All it 'knows' is that it definitely is not a number:
it could be one of an infinite number of other values.

So there is a very, very small chance
one NaN has the same value as another NaN,
but there is an almost infinitely greater chance that it doesn't:

NaN === NaN 
// false 

Nan == NaN 
// false
isNaN()

Use the global JavaScript function isNaN() to find out if a value is a NaN:

let x = 100 / "Apple";
isNaN(x);               
// returns true because x is Not a Number

typeof returns "object" for arrays:

const fruits = ["Banana", "Orange", "Apple", "Mango"];

typeof fruits 
// returns "object" 

Array.isArray(arrayName)

Array.isArray(fruits);   
// returns true 

instanceof

fruits instanceof Array;   
// returns true 

Data Type Conversion

Original
Value
Converted
to Number
Converted
to String
Converted
to Boolean
false 0 'false' false
true 1 'true' true
0 0 '0' false
1 1 '1' true
'0' 0 '0' true
'000' 0 '000' true
'1' 1 '1' true
NaN NaN 'NaN' false
Infinity Infinity 'Infinity' true
-Infinity -Infinity '-Infinity' true
'' (or "") 0 '' (or "") false
'20' 20 '20' true
'twenty' NaN 'twenty' true
[] 0 '' true
[20] 20 '20' true
[10, 20] NaN '10, 20' true
['twenty'] NaN 'twenty' true
['ten','twenty'] NaN 'ten, twenty' true
function(){} NaN 'function(){}' true
{} NaN '[object Object]' true
null 0 'null' false
undefined NaN 'undefined' false

When JavaScript tries to operate on a "wrong" data type,
it will try to convert the value to a "right" type.

The result is not always what you expect

5 + null    
// returns 5 because null is converted to 0

"5" + null  
// returns "5null" because null is converted to "null"

"5" + 2    
// returns "52" because 2 is converted to "2"

"5" - 2     
// returns 3 because "5" is converted to 5

"5" * "2"  
// returns 10  because "5" and "2" are converted to 5 and 2

Adding Strings and Numbers

If you put a number in quotes,
the rest of the numbers will be treated as strings,
and concatenated.

If you add a number and a string, the result will be a string.

var x = 2 + 3 + "5" // 55
x = "5" + 2 + 3; // 523
y="5" + 5; //55
z ="Hello"+5; // Hello5

var x = 10;
var y = 20;
var z = "The result is: " + x + y;
// A common mistake is to expect this result to be 30
// The result is: 1020

var x = 10;
var y = 20;
var z = "30";
var result = x + y + z;
// A common mistake is to expect this result to be 102030
//3030

Other Operations on Numeric Strings

JavaScript strings can have numeric content
JavaScript will try to convert strings to numbers in all numeric operations

var x = 100;         // x is a number
var y = "10";       // y is a string
var z = x / y;       // z will be 10

var x = "100";
var y = "10";
var z = x + y;       // z will not be 110 (It will be 10010)
// JavaScript uses the + operator to concatenate the strings

These methods are not number methods, but global JavaScript methods.

JavaScript global methods can be used on all JavaScript data types.

Example Explanation
Number(true);          // returns 1
Number(false);         // returns 0
Number(“”);              // returns 0
Number("10");          // returns 10
Number("  10");        // returns 10
Number("10  ");        // returns 10
Number(" 10  ");       // returns 10
Number("10.33");       // returns 10.33
Number("10,33");       // returns NaN
Number("10 33");       // returns NaN 
Number("John");        // returns NaN
Number(new Date("2017-09-30"));    
// returns 1506729600000
// number of milliseconds since 1.1.1970

d = new Date();
d.getTime()        
// returns 1404568027739
Number()

converts JavaScript variables to numbers.

If the number cannot be converted,
NaN (Not a Number) is returned.

Number() can also convert a date to a number.

Strings containing numbers (like "3.14")
convert to numbers (like 3.14).

Empty strings and false convert to 0.
True converts to 1.

Anything else converts to NaN (Not a Number)

parseInt('17', 10); // 17
parseInt('123'); // 123
parseInt('11', 2); // 3
parseInt('a1', 10); // Nan
parseInt('2b', 10); // 2
parseInt("10");         // returns 10
parseInt("10.33");      // returns 10
parseInt("10 20 30");   // returns 10
parseInt("10 years");   // returns 10
parseInt("years 10");   // returns NaN 
parseInt(string, radix);

Parses its argument and returns an integer.

Parses a string and returns a whole number.
Spaces are allowed.
Only the first number is returned.

If the number cannot be converted, NaN (Not a Number) is returned.

parseFloat("10");        // returns 10
parseFloat("10.33");     // returns 10.33
parseFloat("10 20 30");  // returns 10
parseFloat("10 years");  // returns 10
parseFloat("years 10");  // returns NaN
parseFloat()
Parses its argument and returns a floating point number.

Parses a string and returns a number.
Spaces are allowed.
Only the first number is returned.

If the number cannot be converted, NaN (Not a Number) is returned.

var y = "5";      // y is a string
var x = + y;      // x is a number
unary + operator

converts a variable to a number

If the variable cannot be converted,
it will still become a number,
but with the value NaN (Not a Number)

String() and toString()
both convert to a string

  1. numbers,
  2. literals,
  3. variables,
  4. expressions
  5. booleans
  6. dates
toString() String()
Boolean
true.toString()    
// returns "true"
String(false)      
// returns "false"
Number
let x = 123;
x.toString()
// returns 123 from variable x

(123).toString()
// returns 123 from literal 123

(100 + 23).toString()
// returns 123 from expression 100 + 23
String(x)         
// number variable x -> str
String(123)       
// number literal 123 -> str
String(100 + 23)  
// number from expression -> str
Date
String(Date())  
// "Thu May 22 2020"
Date().toString()  
// "Thu May 22 2020"

Note: JavaScript automatically calls
the variable's toString() function
when you try to "output" an object or a variable

toString converts:

document.getElementById("demo").innerHTML = myVar;

// if myVar equals to ... the result is:
myVar = [1,2,3,4]       // "1,2,3,4"
myVar = new Date()      // "Fri Jul 18 2014 09:08:55 GMT+0200"
myVar = {name:"John"}  //"[object Object]"

Example Explanation
const fruits = ["Banana", "Orange", "Apple", "Mango"];

document.getElementById("demo").innerHTML =
 fruits.toString();  

Same as:

document.getElementById("demo").innerHTML = fruits

// Banana,Orange,Apple,Mango
toString()

converts an array to a string of (comma separated) array values.

JavaScript automatically converts an array to a comma separated string when a primitive value is expected.
This is always the case when you try to output an array.

All JavaScript objects have a toString() method.

const fruits = ["Banana", "Orange", "Apple", "Mango"];

document.getElementById("demo").innerHTML = 
fruits.join(" * ");  

// Banana * Orange * Apple * Mango
join()

converts an array to a string of array values,
you can specify the separator

Error Handling

When an error occurs, JavaScript will normally stop and generate an error message.

The technical term for this is: JavaScript will throw an exception (throw an error).

JavaScript will actually create an Error object with two properties:

  1. name - sets or returns an error name
  2. message - sets or returns an error message (a string)

  1. EvalError
    An error has occurred in the eval() function
    Newer versions of JavaScript do not throw EvalError.
    Use SyntaxError instead.
  2. RangeError
    A number "out of range" has occurred
    Number is outside the range of legal values.
  3. ReferenceError
    An illegal reference has occurred
    Used (referenced) variable has not been declared
  4. SyntaxError
    A syntax error has occurred
    You cannot evaluate code that contains a syntax error
  5. TypeError
    A type error has occurred
    Used value is outside the range of expected types
    e.g. You cannot convert a number to upper case
  6. URIError
    An error in encodeURI() has occurred
    Thrown if illegal characters in a URI function are used
    e.g. You cannot URI decode percent signs

  1. JavaScript statements try and catch come in pairs
  2. The try statement
    defines a block of code to be tested for errors
    while it is being executed.
  3. The catch statement
    defines a block of code to be executed,
    if an error occurs in the try block.

Syntax:

try {
  // block of code to try
}
catch(err) {
  // block of code to handle errors
}

Example:

<p id="demo"></p>
<script>
try {
  addAlert("Welcome guest!");
}
catch(err) {
  document.getElementById("demo").innerHTML = err.message;
}
</script>  
// addAlert is not defined
// JavaScript catches adddlert as an error, 
// and executes the catch code to handle it.

  1. The throw statement
    allows to create a custom error message.
  2. The exception can be
    1. a JavaScript String
    2. a Number,
    3. a Boolean
    4. or an Object
  3. If you use throw together with try and catch,
    you can control program flow
    and generate custom error messages.
<p>Please input a number between 5 and 10:</p>

<input id="demo" type="text">
<button type="button" onclick="myFunction()">Test Input</button>
<p id="p01"></p>

<script>
function myFunction() {
  var message, x;
  message = document.getElementById("p01");
  message.innerHTML = "";
  x = document.getElementById("demo").value;
  try { 
    if(x == "") throw "empty";
    if(isNaN(x)) throw "not a number";
    x = Number(x);
    if(x < 5) throw "too low";
    if(x > 10) throw "too high";
  }
  catch(err) {
    message.innerHTML = "Input is " + err;
  }
}
</script>  
// Input is empty/not a number/too low/too high

The finally statement lets to execute code,
after try and catch,
regardless of the result.

try {
  block of code to try
}
catch(err) {
  block of code to handle errors
} 
finally {
  block of code to be executed 
  regardless of the try / catch result
}
<p>Please input a number between 5 and 10:</p>

<input id="demo" type="text">
<button type="button" onclick="myFunction()">Test Input</button>

<p id="p01"></p>

<script>
function myFunction() {
  var message, x;
  message = document.getElementById("p01");
  message.innerHTML = "";
  x = document.getElementById("demo").value;
  try { 
    if(x == "")  throw "is empty";
    if(isNaN(x)) throw "is not a number";
    x = Number(x);
    if(x > 10)   throw "is too high";
    if(x < 5)  throw "is too low";
  }
  catch(err) {
    message.innerHTML = "Input " + err;
  }
  finally {
    document.getElementById("demo").value = "";
  }
}
</script> // Input is empty/not a number/too low/too high

Debugging

Debugger
stops the execution of JavaScript,
and calls (if available) the debugging function

HTML Elements

In the HTML DOM object model,
the document object represents your web page.

The document object is the owner
of all other objects in your web page.

If you want to access objects in an HTML page,
you always start with accessing the document object.

Example Explanation
document.getElementById("demo").innerHTML =
"My First JavaScript Function";

<p id="intro">Hello World!</p>
<script>
x = document.getElementById("intro");
document.write("<p>The text from the intro paragraph: " 
+ x.innerHTML + "</p>");
</script>
document.getElementById(id)

finds an element by element id

document.getElementsByClassName("intro");
document.getElementsByClassName()

finds all HTML elements with the same class name

<div id="main">
    <p>The DOM is very useful.</p>
</div>

<script>
    const x = document.getElementById("main");
    const y = x.getElementsByTagName("p");

    document.write('First paragraph inside "main" is ' 
	+ y[0].innerHTML);
</script>
document.getElementsByTagName()

finds all HTML elements with the same tag name

Example Explanation
finds form with id = "frm1"
in the forms collection,
and displays all element values:

const x = document.getElementById("frm1");
let txt = "";

for (let i = 0; i < x.length; i++) {
  txt = txt + x.elements[i].value + "<br>";
 }
 
document.getElementById("demo").innerHTML=txt;
document.forms[]
Read more >>>
var ilist = document.images;

for(var i = 0; i < ilist.length; i++) {
    if(ilist[i].src == 'banner.gif') {
        // found the banner
    }
}
document.images[]
Read more >>>
const links = document.links;
for(let i = 0; i < links.length; i++) {
  let linkHref = document.createTextNode(links[i].href);
  const lineBreak = document.createElement("br");
  document.body.appendChild(linkHref);
  document.body.appendChild(lineBreak);
}
document.links[]
Read more >>>
if (document.anchors.length >= 5) {
  dump("dump found too many anchors");
  window.location = "http://www.google.com";
}
document.anchors[]
Deprecated, read more >>>

Example Explanation
Syntax

element.innerHTML =
document.getElementById(id).innerHTML= new HTML

Example:

<p id = "p1">Hello World!</p>
<script>
    document.getElementById("p1").innerHTML = "New text!";
</script>

<p id = "intro">Hello World!</p>
<script>
    const txt = document.getElementById("intro").innerHTML;
    document.write(txt);
</script>
innerHTML

Get or change any HTML element

Syntax

element.attribute =
document.getElementById(id).attribute = new value

Example:

<img id="image" src="smiley.gif">

<script>
document.getElementById("image").src="landscape.jpg";
</script>
// Change the value of the src attribute of an <img> element
element.attribute

Changing the the value of an HTML attribute of an HTML element

Syntax

element.setAttribute(attribute,value)
element.setAttribute()

Changing the attribute of an HTML element

Syntax

element.style.property =
document.getElementById(id).style.property = new style

Example

document.getElementById("p2").style.color = "blue";

document.getElementById("demo").style.fontSize = "35px"
element.style.Property

Changing the style of an HTML element

Example Explanation

document.createElement()

Create an HTML element


document.removeChild()

Remove an HTML element


document.appendChild()

Add an HTML element


document.replaceChild()

Replace an HTML element

HTML Events

HTML events
are "things" that happen to HTML elements.

An HTML event can be something the browser does,
or something a user does.

JavaScript can "react" on these events and execute code when events are detected.

Event handlers
can be used to handle, and verify, user input, user actions, and browser actions:

  1. Things that should be done every time a page loads
  2. Things that should be done when the page is closed
  3. Action that should be performed when a user clicks a button
  4. Content that should be verified when a user inputs data

Many different methods can be used to let JavaScript work with events:

  1. HTML event attributes can execute JavaScript code directly
  2. HTML event attributes can call JavaScript functions
  3. You can assign your own event handler functions to HTML elements
  4. You can prevent events from being sent or being handled
Example Explanation
Syntax

<element event='some JavaScript'>
<element event="some JavaScript">

Example:

<button 
    onclick="document.getElementById('demo').innerHTML 
    = Date()">The time is?
</button>

<button onclick="this.innerHTML=Date()">
    The time is?
</button>
Assign Events to HTML Event Attributes

<button id="myBtn">Try it</button>

<script>
    document.getElementById("myBtn").onclick=function(){displayDate()};
    function displayDate(){
        document.getElementById("demo").innerHTML=Date();
    }
</script>

<p id="demo"></p>
Assign Events Using the HTML DOM

Example Explanation
<div onmousedown="mDown(this)">
    Click Me
</div>

<script>

    function mDown(obj){
        obj.style.backgroundColor="#1ec5e5";
        obj.innerHTML="Release Me"
    }
	
</script>
onmousedown
The onmousedown, onmouseup, and onclick events
are all parts of a mouse-click.

First when a mouse-button is clicked,
the onmousedown event is triggered,

<div onmouseup="mUp(this)">
    Click Me
</div>

<script>

	function mUp(obj){
        obj.style.backgroundColor="#D94A38";
        obj.innerHTML="Thank You"
    }
	
</script>
onmouseup
then, when the mouse-button is released,
the onmouseup event is triggered,
Syntax

document.getElementById(id).onclick=function(){code}

Example:

<h1 id="id1">My Heading 1</h1>
<button type="button" 
    onclick="document.getElementById('id1').style.color='red'">
    Click Me!
</button>
<h1 onclick="this.innerHTML='Ooops!'">Click on this text!</h1>
<script>
    function changetext(id){
        id.innerHTML="Ooops!";
    }
</script>

<h1 onclick="changetext(this)">Click on this text!</h1>
onclick

finally, when the mouse-click is completed,
the onclick event is triggered.

<div 
    onmouseover="mOver(this)" 
	onmouseout="mOut(this)">
	Mouse Over Me
</div>

<script>
    
	function mOver(obj){
        obj.innerHTML="Thank You"
    }

    function mOut(obj){
        obj.innerHTML="Mouse Over Me"
    }
	
</script>
onmouseover
onmouseout

The onmouseover and onmouseout events
can be used to trigger a function
when the user mouses over, or out of, an HTML element.


onmousemove


onkeydown
onkeypress
onkeyup

<body onload="checkCookies()">

<script>

    function checkCookies(){
        if (navigator.cookieEnabled==true){
          alert("Cookies are enabled")
        } else {
          alert("Cookies are not enabled")
        }
    }
	
</script>
onload
onbeforeunload
onunload

Triggered when the user enters or leaves the page

onload = browser has finished loading the page

The onload event can be used
to check the visitor's browser type and browser version,
and load the proper version of the web page based on the information.

The onload and onunload events can be used to deal with cookies.


onsubmit

<script>
    function myFunction(){
        var x=document.getElementById("fname");
        x.value=x.value.toUpperCase();
    }
</script>

Enter your name: <input type="text" id="fname" onchange="myFunction()">

<p>When you leave the input field, 
a function is triggered 
which transforms the input text 
to upper case.
</p>
onchange

<script>
    function myFunction(x){
        x.style.background="yellow";
    }
</script>

      Enter your name: <input type="text" onfocus="myFunction(this)">
     
	 <p>When the input field gets focus, 
	  a function is triggered 
	  which changes the background-color.
	  </p>

onfocus


onblur


ondragdrop


oncontextmenu


onreset


onerror

Node JS

Nodejs выполняет несколько задач в одном потоке. Например, при обработке клиентских запросов на сервере не создается дополнительных потоков для каждого пользователя. Все вычисления и взаимодействие с клиентами идёт в рамках одного потока. Отсутствуют накладные расходы на создание, удаление и поддержание пула потоков.

Такая архитектура не позволяет полностью использовать всю мощность сервера, поскольку один поток занимает не более одного ядра процессора. Можно запустить несколько версий приложений на nodejs и наладить между ними взаимодействие по принципу master-slave. Это не является многопоточностью в привычном смысле.

Подробнее о дочерних потоках в nodejs по ссылке https://nodejs.org/api/child_process.html


Leave a Reply or Comment

Your email address will not be published. Required fields are marked *