JavaScript values can be easier to understand when we relate them to everyday scenarios. Let’s explore some of the basic values in JavaScript using simple, real-life examples:
1. NaN (Not a Number)
Imagine you’re trying to calculate the average age of a group, but one person mistakenly enters “hello” instead of their age. This error leads to a result that isn’t a valid number:
In this case, averageAge
is NaN
because you can’t do math with text.
2. 0 (Zero)
Think of a newly added shelf that has no books on it:
Here, booksOnShelf
shows there are no books on the shelf.
3. Undefined
Imagine looking for an item in a box, but it’s missing:
missingItem
is undefined
because it wasn’t given a value, similar to finding an empty box.
4. True
Suppose you’re checking if a light bulb is turned on:
isLightOn
confirms that the light bulb is on.
5. Strings
Think of writing a list of ingredients for a recipe:
recipeIngredients
is a string listing what you need to bake something.
6. Objects
Imagine organizing your kitchen utensils:
kitchenUtensils
holds details about how many of each item you have.
7. Arrays
Picture sorting fruits in a basket:
fruitBasket
is an array with fruits. You can find specific fruits by their position or get the total count.
8. Functions
Think of following a recipe to bake a cake:
bakeCake
is a function that lists the steps for baking, and when you use it, it performs those steps.
JavaScript Value | Code Example | Real-life Analogy | Description |
NaN | const averageAge = ‘hello’ / 5; | Trying to divide “hello” by a number | Occurs when performing invalid math operations with non-numeric values. |
0 | const booksOnShelf = 0; | An empty bookshelf | Represents a count of zero, indicating absence. |
Undefined | let missingItem; | Searching for a missing item in an empty box | A variable declared but not assigned a value, similar to looking for something that isn’t there. |
TRUE | const isLightOn = true; | A light bulb that is turned on | Represents a positive condition, meaning something is true or “on.” |
Strings | const recipeIngredients = ‘flour, sugar, eggs, milk’; | Writing down a recipe list | Stores text or sequences of characters, like making a note of ingredients. |
Objects | const kitchenUtensils = { knives: 5, spoons: 10 }; | Organizing different kitchen utensils | Groups related data into a single entity, like counting utensils by type. |
Arrays | const fruitBasket = [‘apple’, ‘banana’]; | A basket containing various fruits | An ordered list of items, which can be accessed by their position (index). |
Functions | function bakeCake() { … } | Following a recipe to bake a cake | Describes a set of steps or instructions that can be reused and executed. |