JavaScript – Basic Syntax
Values and Literals in JavaScript
• Values are the actual data that variables represent. A value can be a
number, string, object, boolean, etc.
• Literals are fixed values that are represented directly in the code.
• Examples of Literals:
– Numeric Literal: 42, 3.14, 0.5
– String Literal: "hello", 'world'
– Boolean Literal: true, false
– Object Literal: {name: 'John', age: 30}
– Array Literal: [1, 2, 3]
– Null Literal: null
– Undefined Literal: undefined
Values and Literals in JavaScript
• Importance of Literals:
– Literals are the simplest way to represent values directly in the
code. You can assign literals to variables to make use of them.
– let number = 42; // numeric literal
– let greeting = "Hello, world!"; // string literal
– let isActive = true; // boolean literal
Primitive Types in JavaScript
• Primitive types are the basic building blocks in JavaScript. They
represent single values and are immutable (their values cannot be
changed directly).
• List of Primitive Types:
– Number
– String
– Boolean
– Null
– Undefined
– Symbol
– BigInt
Primitive Types in JavaScript
• Characteristics of Primitive Types:
– Immutability: Once assigned, the value of a primitive type
cannot be altered (e.g., changing a string directly is not possible).
– Pass by Value: When assigned to a new variable, the value is
copied, and the new variable gets its own copy (no reference to
the original).
• let x = 10; // Number
• let name = "John"; // String
• let isActive = true; // Boolean
• let notDefined; // Undefined (implicitly assigned)
• let emptyValue = null; // Null
• let uniqueId = Symbol('id'); // Symbol
• let largeNumber = 9007199254740991n; // BigInt
Numbers in JavaScript
• In JavaScript, numbers are represented using a single data type
called Number.
• JavaScript doesn’t distinguish between integer and floating-point
types as some other programming languages do.
• Both types are stored using the same representation, specifically the
IEEE 754 standard for double-precision floating-point arithmetic.
• Types of Numbers:
– Integers: Whole numbers like 10, -3, 42.
– Floating-point numbers: Decimal numbers like 3.14, -0.5, 1.23.
Numbers in JavaScript
• Important Characteristics:
• JavaScript uses the Number type to represent all numbers, both
integers and floating-point.
• It is based on 64-bit floating-point arithmetic, so it can represent a
wide range of values but with some limitations on precision for very
large or very small numbers.
• Examples:
– let integer = 100; // Integer
– let floatingPoint = 3.14; // Floating-point number
– let negative = -50; // Negative integer
Numbers in JavaScript
• Special Numbers:
– Infinity: Represents infinity (positive or negative).
• let positiveInfinity = Infinity;
• let negativeInfinity = -Infinity;
– NaN (Not-a-Number): Represents an invalid number operation.
• let invalid = 0 / 0; // NaN
Numbers in JavaScript
• Integer and Floating Point as a Single Type in JavaScript
– In JavaScript, there is no distinct type for integers and floating-
point numbers. Both are represented using the Number type,
which is based on the IEEE 754 standard for double-precision
floating-point values
• Key Points:
– Unified Type: Both integers and floating-point numbers are
stored using the same 64-bit binary format.
– Precision Issues: Since JavaScript uses floating-point
arithmetic, integers can lose precision in certain situations,
especially with very large numbers.
– Range: JavaScript numbers can represent values between
approximately ±(2^53 - 1) for integers (i.e., 9007199254740991)
and ±(2^1024) for floating-point numbers
Numbers in JavaScript
• Example:
– let integer = 42; // Integer stored as a 64-bit floating point
– let float = 3.14; // Floating point number
Numbers in JavaScript
• Precision and Safe Integers:
– JavaScript ensures precise representation for integers only within
a certain range:
• Safe integers are integers between -(2^53 - 1) and (2^53 - 1).
Numbers outside this range may lose precision.
– let safeInteger = 9007199254740991; // Safe integer
– let unsafeInteger = 9007199254740992; // May lose precision
• [Link]() method is used to check if a number is a
safe integer.
– [Link]([Link](9007199254740991)); // true
– [Link]([Link](9007199254740992)); // false
Numbers in JavaScript
• Special Floating-Point Numbers in JavaScript
– In JavaScript, numbers are represented using 64-bit IEEE 754
double-precision floating-point format.
– This format provides several special values that are important to
understand when working with numbers.
– These special floating-point values are used to represent certain
mathematical concepts that are otherwise difficult to handle with
regular numbers.
Numbers in JavaScript
• Special Floating-Point Numbers:
• Infinity
– Represents an unbounded, infinite number that results from
certain mathematical operations.
– Positive and negative infinity are distinct values:
• Infinity (positive infinity)
• -Infinity (negative infinity)
– Generated by dividing a nonzero number by zero or from
calculations that exceed the maximum finite representable
number.
• Example:
– let positiveInfinity = 1 / 0; // Infinity
– let negativeInfinity = -1 / 0; // -Infinity
• Infinity is often used to represent overflow situations, such as when
the value exceeds the range of numbers that can be represented.
Numbers in JavaScript
• NaN (Not-a-Number)
– A special value that represents an invalid result in mathematical
operations.
– NaN is used when an operation cannot produce a valid number
(e.g., dividing zero by zero or performing operations on non-
numeric values).
– NaN is not equal to any other number, including itself.
• Example:
– let result = 0 / 0; // NaN
– let invalidOperation = [Link](-1); // NaN
Numbers in JavaScript
• Checking for NaN:
– Since NaN is not equal to any value, including itself, we can use
the [Link]() method to check for NaN values.
– [Link]([Link](NaN)); // true
– [Link]([Link](42)); // false
Numbers in JavaScript
• Negative Zero (-0)
– Negative zero is a result of certain operations, such as dividing a
negative number by Infinity or -Infinity.
– It is distinguishable from positive zero in some edge cases,
although its behavior is almost identical to 0.
• Example:
– let negativeZero = -1 / Infinity; // -0
– [Link](negativeZero === 0); // true (in many cases, -0
behaves like 0)
• While negative zero is typically handled like regular zero in most
scenarios, it can be relevant in cases involving very fine-tuned
numerical comparisons (e.g., in certain algorithms or when working
with low-level hardware computations).
Numbers in JavaScript
Special Value Description Example
Infinity Represents infinity 1/0
(positive)
-Infinity Represents negative -1 / 0
infinity
NaN Not-a-Number, result 0 / 0, [Link](-1)
of invalid operation
-0 Represents negative -1 / Infinity
zero
Numbers in JavaScript
• Rounding Errors in JavaScript
– Rounding errors occur in JavaScript due to the limitations of
representing numbers in floating-point format.
– The IEEE 754 standard used by JavaScript cannot exactly
represent all decimal numbers, especially fractions like 0.1, 0.2,
and others that do not have a finite binary representation.
– When these values are stored or manipulated, rounding errors
can occur, leading to results that seem unexpected.
Numbers in JavaScript
• Why Rounding Errors Occur:
– JavaScript represents numbers in binary format, and some
decimal numbers cannot be exactly represented as binary
fractions. For example, the decimal number 0.1 has an infinitely
repeating binary expansion and cannot be stored exactly.
– Examples of Rounding Errors:
• let sum = 0.1 + 0.2;
• [Link](sum); // Output: 0.30000000000000004
• The expected result is 0.3, but due to the way floating-point
numbers are represented internally, the result is
0.30000000000000004. This is a rounding error.
Numbers in JavaScript
• Common Issues Due to Rounding:
– Equality Comparisons: Floating-point values may not always
be equal to what you expect due to rounding errors.
• let a = 0.1 + 0.2;
• [Link](a === 0.3); // false (because of rounding error)
– Accumulating Errors: In operations that involve a series of
arithmetic operations (e.g., summing many floating-point
numbers), rounding errors can accumulate and lead to larger
inaccuracies over time.
– Imprecision in Financial Calculations: Calculations that
require exact precision, such as those in finance, are particularly
prone to errors because of rounding problems.
Numbers in JavaScript
• Handling Rounding Errors:
1. Using toFixed() for Display:
• The toFixed() method can be used to round numbers to a
specified number of decimal places when displaying results,
but it will convert the result to a string.
• let num = 0.1 + 0.2;
• [Link]([Link](2)); // "0.30"
2. Using toPrecision() for More Control:
• toPrecision() allows you to specify the total number of
significant digits in a number.
• let preciseNumber = 0.1 + 0.2;
• [Link]([Link](2)); // "0.3"
Numbers in JavaScript
3. Using Multiplication to Avoid Precision Loss:
– One common workaround is to multiply by a power of 10 to
convert decimals into integers, perform the arithmetic, and then
divide by the same power of 10 afterward.
• let result = (0.1 * 10 + 0.2 * 10) / 10;
• [Link](result); // 0.3
4. Using BigDecimal or Libraries for Precision (For Financial
Calculations):
– For precise financial calculations, you can use arbitrary-
precision libraries like BigDecimal or [Link] to avoid
rounding errors in cases where exact precision is required.
Numbers in JavaScript
• Example using [Link]:
– let Decimal = require('[Link]');
– let result = new Decimal(0.1).plus(new Decimal(0.2));
– [Link]([Link]()); // "0.3"
Numbers in JavaScript
5. Equality Tolerance (Using [Link] for Comparison):
– When comparing floating-point numbers, instead of checking for
exact equality, it is better to check if the numbers are "close
enough" using a small tolerance value.
– let a = 0.1 + 0.2;
– let b = 0.3;
– let tolerance = 0.0000001;
– [Link]([Link](a - b) < tolerance); // true