Joy Gupta

Feb 15, 2025 • 10 min read

Up and Going

Breaking Down the Core Concepts of JavaScript: From Statements and Expressions to Loops and Conditionals

In the series "You Should Know JS", in this article we will explore fundamental JavaScript concepts, including statements, expressions, variables, operators, conditionals, loops, and more, providing a solid foundation for mastering JavaScript.

STATEMENTS

In a computer language, a group of words, numbers, and operators that perform a specific task is a statement.

a = b * 2;
  • The characters a and b are called variables.

  • The 2 is just a value itself, called a literal value because it stands alone without being stored in a variable.

  • The = and * characters are operators. They perform actions with the values and variables such as assignment and mathematic multiplication.

EXPRESSIONS

The above statement has four expressions in it:

  • 2 is a literal value expression.

  • b is a variable expression, which means to retrieve its current value.

  • b * 2 is an arithmetic expression, which means to do the multiplication.

  • a = b 2 is an assignment expression, which means assigning the result of the b * 2 expression to variable a (more on assignments later).

There is one more type of expression called function call expression which is an expression calling a function like alert(“Hello”)

A general expression that stands alone is also called an expression statement, such as b * 2;.

INPUT

There are 2 ways to take input

  • prompt

  • HTML to create input elements and use JS to read those values

OPERATORS

Please check usage of Object property access. Its interesting to know “.” has its own name.


EXTRAS

Q. Have you ever wondered how “99.99” == 99.99 evaluates to true in JS?

It must be because when we use double equal (i.e. loose-equals) it does not check for the datatype. Right? Not really!

When you use the loose-equals operator to make the comparison "99.99" == 99.99, JavaScript will convert the left-hand side "99.99" to its number equivalent to 99.99. The comparison then becomes 99.99 == 99.99, which is of course true. To help you out in these common situations where you are comparing one datatype with another, JavaScript will sometimes kick in and implicitly coerce values to the matching types.


COMMENTS

Comments should explain why, not what. They can optionally explain how what’s written is particularly confusing.

var a = 42; // Single Line

/* The following value is used because
 it has been shown that it answers
 every question in the universe. */
var a = 42;

var a = /* arbitrary value */ 42;

VARIABLES

JavaScript uses the latter approach, dynamic typing, meaning variables can hold values of any type without any type of enforcement.

By convention, JavaScript variables as constants are usually capitalized, with underscores _ between multiple words.

//Global Variables
var TAX_RATE = 0.08; // 8% sales tax

var amount = 99.99;
amount = amount * 2;
amount = amount + (amount * TAX_RATE);
console.log( amount ); // 215.9784
console.log( amount.toFixed( 2 ) ); // "215.98"

BLOCKS

A block is defined by wrapping one or more statements inside a curly-brace pair { .. }.

This kind of standalone { .. } general block is valid but isn’t as commonly seen in JS programs. Typically, blocks are attached to some other control statement eg if, loop, or functions; then only they make sense.

CONDITIONALS

Conditional statements control behavior in JavaScript and determine whether or not pieces of code can run.

const ACCESSORY_PRICE = 9.99;
var bank_balance = 302.13;
var amount = 99.99;
amount = amount * 2;
// can we afford the extra purchase?
if ( amount < bank_balance ) {
 console.log( "I'll take the accessory!" );
 amount = amount + ACCESSORY_PRICE;
}
else {
 console.log( "No, thanks." );
}

The if statement expects a boolean, but if you pass it something that’s not already a boolean, coercion will occur.

JavaScript defines a list of specific values that are considered “falsy” because when coerced to a boolean, they become false—these include values like 0 and "".

LOOPS

while (numOfCustomers > 0) {
 console.log( "How may I help you?" );
 // help the customer...
 numOfCustomers = numOfCustomers - 1;
}

// verses:
do {
 console.log( "How may I help you?" );
 // help the customer...
 numOfCustomers = numOfCustomers - 1;
} while (numOfCustomers > 0);

//verses:
for (var numOfCustomers = 10; i > 0; numOfCustomers = numOfCustomers - 1) {
 console.log( "How may I help you?" );
 // help the customer...
 numOfCustomers = numOfCustomers - 1;
}

The only practical difference between these loops is whether the conditional is tested before the first iteration (while) or after the first iteration (do..while). The conditional is tested on each iteration, much as if there is an implied if statement inside the loop.

SCOPE

Technically called lexical scope.

The scope is a collection of variables as well as the rules for how those variables are accessed by name. In JavaScript, each function gets its scope. Only code inside that function can access that function’s scoped variables.

Lexical scope rules say that code in one scope can access variables of either that scope or any scope outside of it.

function one() {
 // this `a` only belongs to the `one()` function
 var a = 1;
 console.log( a );
}
function two() {
 // this `a` only belongs to the `two()` function
 var a = 2;
 console.log( a );
}
one(); // 1
two();

VALUES & TYPES

JavaScript has typed values, not typed variables.

The statement "JavaScript has typed values, not typed variables" means that JavaScript is a dynamically typed language where the data types are associated with values, not with variables. In statically typed languages, like Java or C, the data type of a variable is explicitly declared, and that type is enforced by the compiler. In contrast, JavaScript is dynamically typed, and the type of a variable is determined at runtime based on the type of value it holds.

  1. string

  2. number

  3. null and undefined

  4. object

  5. symbol (new to ES6)

var a;
typeof a; // "undefined"

a = "hello world";
typeof a; // "string"

a = 42;
typeof a; // "number"

a = true;
typeof a; // "boolean"

a = null;
typeof a; // "object"--weird, bug

a = undefined;
typeof a; // "undefined"

a = { b: "c" };
typeof a;

typeof "abc" returns "string", not string.
typeof null returns "object"; and its a bug in JS

OBJECTS

The object type refers to a compound value where you can set properties (named locations) that each hold their own values of any type.

var obj = {
	 a: "hello world",
	 b: 42,
	 c: true
};

Properties can either be accessed with dot notation (i.e., obj.a) or bracket notation (i.e., obj["a"]).

Of course, bracket notation is also useful if you want to access a property/key but the name is stored in another variable, such as:

var obj = {
 a: "hello world",
 b: 42
};
var b = "a";
obj[b]; // "hello world"
obj["b"]; // 42

Why "functions" and "arrays" are not treated as built-in types?

In JavaScript, everything is an object at the core, including arrays and functions. However, the language offers specialized behavior for them, so they aren't just "generic" objects.
JavaScript uses prototypal inheritance, so objects like arrays and functions are built on top of the basic Object prototype but with added methods and properties that make them specialized.

What is "Prototypal Inheritance"?

Prototypal inheritance is a mechanism in JavaScript where objects can inherit properties and methods from other objects. Each object has an internal property called [[Prototype]], which references its prototype object. When accessing a property on an object, if the property is not found directly on the object, JavaScript looks for it in the prototype object, and then in the prototype's prototype, and so on, up the prototype chain until it reaches null.


ARRAYS

An array is an object that holds values (of any type) not particularly in named properties/keys, but rather in numerically indexed positions. Because arrays are special objects, they can also have properties, including the automatically updated length property.

FUNCTIONS

A JavaScript function is a block of code designed to perform a particular task. Functions are a subtype of objects

typeof returns //"function"

Function Statement vs. Function Expression vs Function Declaration vs Anonymous Function vs Named Function vs First-Class Function vs IIFE Functions

  • Function Statement aka Function Declaration

    function functionStatement(){
    	console.log("This is a function statement");
    }
  • Function Expression

    var temporaryFunction = function(){
    	console.log("This is a function expression");
    }

    What is the difference between Function Statement and Function Expression?
    Function Statements are hoisted to the top of the current scope while Function Expressions are not.

    functionStatement();
    functionExpression();
    
    function functionStatement(){
    	console.log("This is a function statement");
    }
    
    var functionExpression = function(){
    	console.log("This is a function expression");
    }
    
    //Output -
    //This is a function statement
    //VM78:2 Uncaught TypeError: functionExpression is not a function
  • Anonymous Function

    function(){
    	console.log("This is a Anonymous function");
    }
  • Named Function

    var namedFunction = function something(){
    	console.log("This is namedFunction");
    }
    
    //Guess the output
    namedFunction();
    something();
  • First Class Function aka First Class Citizen

    The ability of functions to be used as values and can be passed as an argument to another function and can be returned as well is known as the first-class function.

  • IFFE Function: Immediately Invoked Function Expression

    (function IIFE(){
     console.log( "Hello!" );
    })();
    // "Hello!

    Exercise:

    var a = 42;
    (function IIFE(){
     var a = 10;
     console.log( a ); // 10
    })();
    console.log( a ); 

BUILT-IN METHODS

The built-in types and subtypes we’ve just discussed have behaviors exposed as properties and methods.

var a = "hello world";
var b = 3.14159;
a.length; // 11
a.toUpperCase(); // "HELLO WORLD"
b.toFixed(4);

How can we call a.toUpperCase() even though 'a' is a string? Why is 'a' behaving like an object here?

Ref: https://www.linkedin.com/feed/update/urn:li:activity:7139195703431532545/

StackOverflow: https://stackoverflow.com/questions/9108925/how-is-almost-everything-in-javascript-an-object

HOISTING

The process whereby the interpreter appears to move the declaration of functions, variables, classes, or imports to the top of their scope, before execution of the code.

When a var declaration is conceptually “moved” to the top of its enclosing scope. We will talk more about Hoisting in later on chapters.

var a = 2;
foo(); // works because `foo()` declaration is "hoisted"
function foo() {
 a = 3;
 console.log( a ); // 3
 var a; // declaration is "hoisted" to the top of `foo()`
}
console.log( a ); // 2

functionExpression(); // here it is undefined -> functionExpression is not a function

var functionExpression = function(){
	console.log("This is a function expression");
}


NESTED SCOPES

When you declare a variable, it is available anywhere in that scope, as well as any lower/inner scopes. For example:

function foo() {
	 var a = 1;
	 function bar() {
		 var b = 2;
		 function baz() {
			 var c = 3;
			 console.log( a, b, c ); // 1 2 3
		 }
		 baz();
		 console.log( a, b ); // 1 2
	 }
	 bar();
	 console.log( a ); // 1
}
foo();


SRTICT MODE

  • ES5 added a “strict mode” to the language

  • Applies restrictions are seen as keeping the code to a safer and more appropriate set of guidelines

  • strict mode makes your code generally more optimizable by the engine;

  • disallowing the implicit auto-global variable declaration from omitting the var

function foo() {
  "use strict"; // turn on strict mode
   a = 1; // `var` missing, ReferenceError
}
foo();


CLOSURES

You can think of closure as a way to “remember” and continue to access a function’s scope (its variables) even once the function has finished running.

function outerFunction(x) {
	 // parameter `x` is an inner variable
	 // inner function `add()` uses `x`, so
	 // it has a "closure" over it
	 function innerFunction(y) {
		 return y + x;
	 };
	 return innerFunction;
}

var func = outerFunction( 1 ); //plusOne is now termed as reference
func( 3 ); 
  • The scope chain: When the innerFunction is returned from the outerFunction, it "closes over" the outerFunction's variables. his means that the execution context of innerFunction remembers the environment in which it was created.

  • The closure’s environment: The closure keeps a reference to the outer function’s variables, not copies of them. This means that outerVariable is not physically stored inside the closure itself, but rather the closure retains a reference to the scope in which it was defined, even after that scope has been destroyed.

  • Memory in the heap: When closures are created, the variables from the enclosing function are typically stored in the heap memory (in the environment or scope object). This is where the closure's "lexical environment" is kept. As long as the closure exists, the environment remains accessible.

Join Joy on Peerlist!

Join amazing folks like Joy and thousands of other people in tech.

Create Profile

Join with Joy’s personal invite link.

0

6

0