Types, Values, and Variables in Javascript

Types

Dheeraj Singh
Groww Engineering

--

The kinds of values that can be represented and manipulated in a programming language are known as types, one of the most fundamental characteristics of a programming language is the set of types it supports.

Values

Computer programs work by manipulating values, such as 3.14 or “Hello World”.

Variables

When a program needs to retain a value for future use, it assigns the value to (or stores the value in) a variable. The way variables work is a fundamental characteristic of any programming language.

Two main Data Types in JavaScript

Types

4 Kinds of Types in Javascript
4 kinds of Types in Javascript

Numbers

Number (Javascript’s primary numeric type), is used to represent integers and to approximate real numbers. When a number appears directly in a Javascript program, it is called a numeric literal.

Javascript represents numbers using the 64-bit floating point format defined by IEEE 754 standard. (Same as double in Java, C++ and in most modern programming languages)

Types of Number Literals
Types of Number Literals

Arithmetic in Javascript

Operators that can be used with Numeric Literals are +(addition), -(subtraction), *(multiplication), /(division), %(modulo). ES6 adds ** for exponentiation.

Apart from these basic operators, Javascript also supports complex mathematical operations through a set of functions and constants defined as properties of the Math object. Examples:

Math.pow(2, 53);     // 2 to the power 53
Math.abs(-5); // absolute value of -5

ES6 defines even more functions in Math object.

Binary Floating-Point and Rounding Errors

The IEEE-754 floating-point representation used by Javascript (and just about every other modern programming language) is a binary representation of the decimal numbers we use in our daily lives. So the numbers are very precise in Javascript but still cannot represent numbers such as 0.1 to their exact value. For example:

let x = .3 - .2;    // thirty cents minus 20 cents
let y = .2 - .1; // twenty cents minus 10 cents
x === y // => false: the two values are not the same
x === .1 // => false: .3-.2 is not equal to .1

To solve this, we can use scaled integers. For example, using integer paise instead of fractional rupees.

Arbitrary Precision Integers with BigInt

A new numeric type BigInt is added in ES2020, whose values are Integers and can represent 64-bit integers. BigInt literals are written as a string of digits followed by a lowercase letter n. BigInt doesn’t support floating-point/real numbers. Examples:

1234n                // A decimal BigInt literal
0b111111n // A binary BigInt
0o7777n // An octal BigInt

Dates and Times

Javascript defines a simple Date class for representing and manipulating the numbers that represent dates and times.

Javascript Dates are objects, but they also have a numeric representation as a timestamp that specifies the number of elapsed milliseconds since January 1, 1970. Usage:

let timestamp = Date.now();   // Current time as a timestamp
let now = new Date(); // Current time as date

Text

JavaScript type for representing text is String.

String is an immutable, ordered sequence of 16-bit values that typically represents a set of Unicode characters with UTF-16 encoding.

String uses zero-based indexing: the first 16-bit value is at position 0, the second at position 1, and so on.

String Literals

To include a string within a JS program, simply include it within a matched pair of single or double quotes or back ticks. Examples:

'String defined with single quote' 
"String defined with double quotes"
`String defined with back ticks`

Double quote and back tick strings may be contained within strings delimited by single quote characters, and similarly for strings delimited by double quotes or back ticks. Example of a delimited string:

`"She said 'hi'", he said.`

Working with Strings

In JS, strings can be used to concatenate strings using +. If used with numbers + will add them. But if you add this operator to strings, it appends the second string to the first string. Example:

let msg = "Hello, " + "world";   // Returns string "Hello, world"

Comparison of strings can be done with standard === equality, !== inequality, <, <= and >, >= operators.

length property of the string determines the length of the string.

Javascript provides a rich API for working with strings which provides properties like length (determines length of a string), substring, slice, splice, split etc. These methods (except length, which returns a number) return new strings because Strings are immutable in Javascript.

Strings can be treated like read-only arrays. Characters of strings can be accessed same as array elements. Example:

let s = "Hello";          // Declare a variable with string "Hello"
s[0]; // Returns H

Template Literals

In ES6 and later, string literals can be delimited with back ticks: called template literals. Template literals can include arbitrary JavaScript expressions. Example:

let name = "John";
let greeting = `Hello ${ name }`; // greeting == "Hello John"

Everything between the ${ and the matching } is interpreted as a JavaScript expression.

A template literal may include any number of expressions. It can use any of the escape characters that normal strings can, and it can span any number of lines, with no special escaping required.

Pattern Matching

JavaScript defines a data type known as a regular expression (or RegExp) for describing and matching patterns in strings of text. Example:

/[1-9][0-9]*/; // Match a nonzero digit, followed by any # of digits

Methods used by RegExp objects are: text, search, match, replace split etc.

Boolean Values

A boolean value represents truth or falsehood, on or off, yes or no. There are only two possible values of this type. The reserved words true and false evaluate to these two values.

undefined, null, 0, -0, NaN, “” are all called falsy values.

All other values, including all objects (and arrays) convert to, and work like, true. So they are called truthy values.

null and undefined

Both null and undefined are sole members of their special types. They can often be used interchangeably. Both are falsy values.

null

null symbolizes absence of value. It is a special object (type of null is object) that indicates no object.

null signifies a program-level, normal, or expected absence of value.

undefined

undefinedsymbolizes a deeper kind of absence. Meaning that the values have not been initialized. Its type is undefined.

undefined signifies a system-level, unexpected, or error-like absence of value.

Symbols

Symbols were introduced in ES6 to serve as non-string property names for JS Objects. Example:

let symbolName = Symbol("propname");

To obtain a Symbol value, you call the Symbol() function. This function never returns the same value twice, even when called with the same argument.

Symbol.for()returns the same value if called on same strings as arguments twice, unlike Symbol() function which always returns unique values.

The Global Object

The Global Object is a regular JavaScript object that has globally defined identifiers as properties that are available to a JavaScript program.

When a JS interpreter starts, or a web browser loads a new page, it creates a new global object and gives it an initial set of properties that define 4 things: Global constants, Global functions, Constructor functions and Global objects. Examples: undefined, null, Date() etc.

In Node, global object can be accessed with keyword global.

In browsers, window object serves as Global Object.

ES2020 defines globalThis as the standard way to refer to the global object in any context. (Implemented by all modern browsers and Node).

Immutable Primitive Values and Mutable Object References

Primitives

  • Primitives in JavaScript are immutable.
  • Primitives are compared by value.

Objects

  • Objects in JavaScript are mutable.
  • Objects are compared by reference. (2 Objects having same key value properties are not equal because their reference is different)
  • To compare the key-value pairs inside an object or array, we must compare their properties or values explicitly. Example:
let a = [];   // The variable a refers to an empty array.
let b = a; // Now b refers to the same array.
b[0] = 1; // Mutate the array referred to by variable b.
a[0]; // => 1: the change is also visible through variable a
a === b; // => true; as a and b refer to same object

Type Conversions

JavaScript is very flexible about the types of values it requires. you may supply a value of any type, and JavaScript will convert it as needed

Conversions and Equality

=== checks for type also. == checks just for values and is more flexible. If two different types are provided to == operator then it will convert one of operand to another type and compare the values.

Explicit Conversions

Although JavaScript performs many type conversions automatically, but sometimes we need to perform an explicit conversion, or you may prefer to make the conversions explicit to keep your code clearer.

Boolean(), Number() and String() functions explicitly convert values. Examples:

Number("3");    // => 3
String(false); // => "false": Or use false.toString()
Boolean([]); // => true

Object to Primitive Conversions

Objects to Primitive conversions consist of complicated rules in JS.

JavaScript specification defines three fundamental algorithms for converting objects to primitives: prefer-string, prefer-number and no-preference.

Variables

Variable Declaration and Assignment

The term “variable” implies that new values can be assigned: that the value associated with the variable may vary as our program runs. If we permanently assign a value to a name, then we call that name a constant instead of a variable. Before you can use a variable or constant in a JavaScript program, you must declare it

Pre-ES6, variables were declared with var. ES6 and later, they can be declared with let and const. Examples:

let message = "hello";
let i = 0, j = 0, k = 0;
let x = 2, y = x*x;
const C = 299792.458;

Differences between let, const and var

  • let and const are block scoped. var does not have block scope.
    Although var is contained to the body of the function no matter how deeply its nested.
  • let and const, if defined at top level, declaration is global scoped (In node and client side modules, global scope is the file it is defined in. In browsers, global scope is the HTML document).
    Whereas, Globals declared with var are implemented as properties of the global object.
  • Same identifier with more than one let or const the declaration gives a syntax error.
    While it is legal to declare the same identifier as variable multiple times with var.
  • Hoisting happens with var declarations. So it can be used before it is initialized in the enclosing function. (Value of the variable maybe undefined if we use it above its declaration because it is not yet initialized, but the definition is moved to the top so it does not give an error to use it(can result in time taking bugs)).
    Variables declared with let and const are also hoisted but, unlike var , are not initialized with a default value. An exception will be thrown if a variable declared with let or const is read before it is initialized.

Destructuring Assignment

  • In a destructuring assignment, the value on the right hand side of the equals sign is an array or object (a “structured” value), and the lefthand side specifies one or more variable names using a syntax that mimics array and object literal syntax. Example:
let [x, y] = [1,2];         // Same as let x=1, y=2
let [x, ...y] = [1,2,3,4]; // y == [2,3,4] (... used to assign all remaining values to a single variable)

Next Steps

These next few posts will be part of a series discussing basics and advanced topics in JavaScript.

If you’ve enjoyed this story, please click the 👏 button and share it, so that others can find it as well! Also, feel free to leave a comment below.

Groww Engineering publishes technical anecdotes, the latest technologies, and better ways to tackle common programming problems. You can subscribe here to get the latest updates.

We are hiring. View job openings here.

--

--