Variables hold the values that a script works with. JavaScript decides their types at run time.
Declaring Variables
JavaScript has three keywords for variables. var is the old form; it is function-scoped and can be re-declared, which causes bugs. let (ES6) is block-scoped and can be changed. const (ES6) is block-scoped and cannot be re-assigned; it must be given a value when declared. Modern code uses const by default and let when a value must change. Names may contain letters, digits, _ and $, cannot start with a digit, and are case-sensitive.
Definition: Dynamic typing. A feature of JavaScript in which the type of a variable is decided by the value it currently holds, at run time, so that the same variable may hold values of different types.
Data Types
JavaScript is dynamically typed: a variable takes the type of its value. The primitive types are number (integers and decimals, plus Infinity and NaN, "not a number"), string (text in single, double or back quotes), boolean (true, false), undefined (a declared variable with no value), null (an intentional empty value), bigint and symbol. The object type covers objects, arrays and functions. The typeof operator gives the type of a value. Template literals, in back quotes, allow embedded expressions: Total: ${price * qty}.
Type Conversion and Comparison
JavaScript converts types automatically in some operations, which can surprise: "5" + 2 gives "52" (string), but "5" 2 gives 10. Number("42") and parseInt("42") convert strings to numbers, and String(42) converts a number to a string. == compares after converting types, so 5 == "5" is true, while ===* (strict equality) compares type and value, so 5 === "5" is false. Strict equality should normally be used.
Arrays
An array is an ordered list of values, written in square brackets: const marks = [78, 85, 62];. Elements are indexed from 0, and length gives the number of elements. Arrays can hold mixed types and grow automatically. Useful methods are push() (add at the end), pop() (remove from the end), unshift() and shift() (at the start), indexOf(), includes(), slice(), splice(), join(), sort() and reverse(). Higher-order methods take a function: forEach() runs it on each element, map() builds a new array, filter() keeps elements that pass a test, and reduce() combines them into one value.
Table 3.2: JavaScript data types
| Type | Example | typeof gives |
|---|---|---|
| number | 42, 3.14 | "number" |
| string | "Java", 'BCA' | "string" |
| boolean | true | "boolean" |
| undefined | let x; | "undefined" |
| object | [1, 2], {a: 1} | "object" |
Example 3.2: Working with marks
Problem: Store the marks 78, 85, 62, 91 and 55 in an array. Add 70, find the average, the marks above 75, and the marks sorted in descending order.
Solution:
- marks.push(70) adds the new mark.
- reduce adds them up, and dividing by length gives the average.
- filter(m => m > 75) keeps the high marks.
- sort((a, b) => b - a) sorts in descending order.
Result: The script below prints the results.
const marks = [78, 85, 62, 91, 55];
marks.push(70);
const total = marks.reduce((sum, m) => sum + m, 0);
console.log("marks:", marks.join(", "), "| count:", marks.length);
console.log("average:", (total / marks.length).toFixed(2));
console.log("above 75:", marks.filter(m => m > 75));
console.log("descending:", [...marks].sort((a, b) => b - a));
console.log(typeof marks, typeof total, "5" + 2, "5" * 2, 5 === "5");
Output
marks: 78, 85, 62, 91, 55, 70 | count: 6
average: 73.50
above 75: [ 78, 85, 91 ]
descending: [ 91, 85, 78, 70, 62, 55 ]
object number 52 10 false
Common mistakes
- Using var, which leaks out of blocks, instead of let or const.
- Comparing with == and getting surprising conversions; prefer ===.
- Adding a number to a string from prompt and getting joined text, as in "5" + 2 = "52".
Key takeaways
- let and const are block-scoped; const cannot be re-assigned.
- Types are decided at run time; typeof tells the type.
- Use === for comparison.
- Arrays have push, pop, map, filter and reduce.
Practice questions
- Distinguish let and const.
- What is the result of "5" + 2 in JavaScript?
- What does the filter() method do?
Answers to the practice questions
- Both are block-scoped; a let variable can be re-assigned, a const cannot.
- "52", because + joins a string with another value.
- It returns a new array with the elements that pass a test function.
Sources
- Official BCA syllabus Web Technologies, course code 25BCA402SEC02, Unit III
