JavaScript basics

You can see a sample of the exercises.

To see all premium exercises, enter a valid license key or purchase one:


Arrays 01

  1. Create 3 empty arrays e1, e2, e3, in 3 different ways.
  2. Create 2 arrays a1 and a2, containing a single element 1, in 2 different ways.
// Array literal notation
const e1 = [];

// Array constructor function
const e2 = new Array();

// Array.of() method
const e3 = Array.of();

// Array literal notation
const a1 = [1];

// Array.of() method
const a2 = Array.of(1);

This exercise is strange, isn't it? I ask you to create an empty array in 3 different ways, but to create an array containing a single integer in only 2 different ways.

The tasks do not look that different at first sight. But, as weird as it may seem, we cannot create an array containing a single integer with the Array() constructor function. That's because this constructor function has a flaw.

Relevant resource(s):

Numbers 01: decimal fiesta

const a = 0.4 - 0.3;
const b = 0.3 - 0.2;

console.log (a === b);

Without running the previous code, what does it print to the screen?

const a = 0.4 - 0.3;
const b = 0.3 - 0.2;

console.log (a === b); // false

This exercise points out the fact that decimal numbers are not represented with their exact value but with an approximation. Indeed, JavaScript, and almost all other modern programming languages, use the same standard to represent decimal numbers: the IEEE-754 floating-point representation. This representation is a binary representation, which can exactly represent fractions like 1/2, 1/4 or 1/64. But the fractions we use in our base-10 system are fractions like 1/10, 1/10 or 1/100. The binary representation can only approximate very closely these fractions. Because of rounding error, the difference between the approximations of 0.4 and 0.3 is not exactlty the same as the difference between the approximations of 0.3 and 0.2.

It is important to understand that this problem is not specific to JavaScript: it affects any programming language that uses binary floating-point numbers. Also, note that the values a and b in the code above are very close to each other and to the correct value. The computed values are adequate for almost any purpose. The problem only arises when we attempt to compare values for equality.

Object celebration 05

const PROPERTY_NAME = 'p1';
const propertyValue = () => 'p' + 2;

Create an object o that has properties names of p1 and p2 and values of 1 and 2. Use PROPERTY_NAME and propertyValue() to do so.

const PROPERTY_NAME = 'p1';
const propertyValue = () => 'p' + 2;

const o = {
  [PROPERTY_NAME]: 1,
  [propertyValue()]: 2
};

This exercise shows the use of computed property names. This allows to use the value of a variable or the return value of a function invocation as a property name. This requires the use of a specific syntax, with opening and closing square brackets ([]). The square brackets within an object literal notation (between the curly braces) delimit an arbitrary JavaScript expression. The expression is evaluated and the resulting value (converted to a string if necessary) is used as the property name.

On the 1st line, we declare a variable PROPERTY_NAME and we assign it the string value 'p1'.

On the 2nd line, we define a function called propertyValue() by using an arrow function. The function has no parameter and it always returns the same value whenever it is called: the string 'p2'. When using the + operator between a operand that is a string and an operand that is a number, JavaScript performs type conversion so that the expression returns a string consisting of both operands concatenated. Note that you should avoid relying on JavaScript type conversion, as it is tricky and it does not show intent in the code. We use it here only for educational purposes. For professional purposes, we would write this:

const propertyValue = () => 'p2';
// or
const propertyValue = () => 'p' + '2';

Values and variables 05: safari

What variable name is a valid name in JavaScript?

  1. 1elephant
  2. tallGiraffe_1
  3. $crocodile
  4. nice-athletic-camel
  5. wise_small_hippo
  6. zebra2
  7. new
  1. 1elephant: not valid.
  2. tallGiraffe_1: valid.
  3. $crocodile: valid.
  4. nice-athletic-camel: not valid.
  5. wise_small_hippo: valid.
  6. zebra2: valid.
  7. new: not valid.

This exercise tests our knowledge of the rules for naming identifiers in JavaScript.

Identifiers

Custom names in a program are usually referred as identifiers. In JavaScript, the identifiers are:

  • Variable names (including function parameters).
  • Function names (including Class names).
  • Property names of objects.

Valid names for identifiers

In JavaScript, the rules for naming an identifier are the following:

  1. The name of the identifier usually must not be a reserved JavaScript keyword. But even if it can be (for specific keywords only, and in certain circumstances only), the best practice is to avoid all reserved keywords. You can see the full list of the reserved keywords below, in the last section of this document.
  2. The first character of the identifier name must be a letter, an underscore (_) or a dollar sign ($).
  3. The (optional) following characters can be letters, digits, underscores (_) or dollar signs ($).

Identifier names and numbers

An identifier name cannot start with a digit so that JavaScript can distinguish identifier names from numbers.

Recommended letters: ASCII letters

A letter is usually an ASCII letter, i.e. a non-accentuated letter from the latin alphabet. The recommended practice is to only use ASCII letters for identifier names in your code. However, letters from other alphabets are also allowed. That is why the following code, as weird as it looks, does not throw any error:

const àèìòù = 1 // non-ASCII accentuated letters 
const αβΔ = 2; // non-ASCII letters from the greek alphabet

console.log(àèìòù);
console.log(αβΔ);

Specificity of property names of objects

For property names, it is possible to replace an invalid property name with the corresponding name property explicitly written as a string. Let us have a look:

const obj_1 = { my-name: 'chloe'};

Since my-name is an invalid identifier (the dash character - is not allowed), the previous code throws an error (SyntaxError) if we run it.

const obj_2 = { 'my-name': 'halle'};

Since 'my-name' is a string literal, the previous code runs smoothly. But even though this is possible in JavaScript, we recommend you use only valid property names in your code (see next paragraph). Having valid identifiers as property names let you access them with the dot notation (which is preferred over the bracket notation when it is possible).

Recommended case for identifiers

In JavaScript, the common practice is to use a recommended case for specific identifiers. In details:

Identifier Strongly recommended case
Variables that can be reassigned or mutated camelCase (variableWithLetKeyword)
Function parameters camelCase (variableForFunction)
Variables that store constant values UPPERCASE (REAL_CONSTANT)
Variables that store a collection of methods (modules) camelCase (collectionOfMethods)
Property names of an object camelCase (propertyName)
Factory functions PascalCase (FactoryFunction)
Non-factory functions camelCase (ordinaryFunction)

I personnaly do not follow the previous recommendations, because camelCase is less readable than snake_case. Therefore, I only use camelCase for functions. For variables, function parameters and perperty names, I only use snake_case.

Here are the 43 reserved keywords in JavaScript:

  • await (Reserved in module code).
  • break.
  • case.
  • catch.
  • class.
  • const.
  • continue.
  • debugger.
  • default.
  • delete.
  • do.
  • else.
  • enum (For a possible use in a future specification).
  • export.
  • extends.
  • finally.
  • for.
  • function.
  • if.
  • implements (Reserved in strict mode only).
  • import.
  • in.
  • instanceof.
  • interface (Reserved in strict mode only).
  • let (Reserved in strict mode only).
  • new.
  • package (Reserved in strict mode only).
  • private (Reserved in strict mode only).
  • protected (Reserved in strict mode only).
  • public (Reserved in strict mode only).
  • return.
  • static (Reserved in strict mode only).
  • super.
  • switch.
  • this.
  • throw.
  • try.
  • typeof.
  • var.
  • void.
  • while.
  • with.
  • yield.

To see all premium exercises, enter a valid license key or purchase one: