JavaScript Fundamentals Β· Astro Tech Blog

JavaScript Fundamentals

This chapter covers the core building blocks of the JavaScript language. Master these and you’ll have a solid foundation.

Hello, World!

The traditional first program:

console.log("Hello, World!");
// β†’ Hello, World!

In a browser, you can also write directly to the page:

Demo: Hello World in Browser
JavaScript
document.write('<h2>Hello, World!</h2>');
document.write('<p>Welcome to JavaScript!</p>');
Live Output Window

Or create an alert:

Demo: Alert
HTML
<button onclick='alert('Hello!')'>Click me</button>
Live Output Window

Code Structure

Statements

A statement is a single instruction. Statements are separated by a semicolon:

alert("Hello");
alert("World");

Semicolons are optional in most cases β€” JavaScript automatically inserts them (ASI β€” Automatic Semicolon Insertion):

alert("Hello")
alert("World")

But be careful β€” ASI doesn’t always work as expected:

// This works fine
let x = 5
let y = 10

// But this breaks
let a = 5
[1, 2, 3].forEach(console.log)

Rule of thumb: Use semicolons explicitly. It’s safer and clearer.

Comments

Comments are ignored by the engine. Use them to explain your code:

// Single-line comment

/*
  Multi-line
  comment
*/

/**
 * JSDoc comment β€” describes functions
 * @param {string} name
 */
function greet(name) {
  // ...
}

The Modern Mode, β€œuse strict”

For a long time, JavaScript evolved without backward compatibility issues. New features were added without breaking old code. But this meant some old mistakes remained.

The "use strict" directive fixes this by enabling a strict mode that catches common errors:

"use strict";

// Now this throws an error:
// (without strict mode, it silently creates a global variable)
x = 3.14;
// β†’ ReferenceError: x is not defined

Key differences in strict mode:

"use strict";

// 1. No undeclared variables
x = 5; // Error!

// 2. No deleting variables, functions, or arguments
let y = 10;
delete y; // Error!

// 3. Duplicate parameter names not allowed
function sum(a, a, c) {} // Error!

// 4. "this" is undefined in regular functions
function show() {
  console.log(this); // undefined (in non-strict: global object)
}
show();

// 5. No octal literals
let z = 010; // Error!

How to use it

Place "use strict" at the top of your script or function:

"use strict"; // Top of file β€” applies to all code

function myFunc() {
  "use strict"; // Or just inside a function
}

Note: ES6 modules are automatically in strict mode. Classes are also strict by default.

Variables

Variables store data. In JavaScript, we have three ways to declare them:

let

Modern variable declaration. Block-scoped and can be reassigned:

let message = "Hello";
message = "World"; // Reassigning is fine
console.log(message); // β†’ World

const

Declares a constant β€” cannot be reassigned:

const PI = 3.14159;
PI = 3; // TypeError: Assignment to constant variable

const does NOT make the value immutable β€” only the binding. For objects:

const user = { name: "Alice" };
user.name = "Bob"; // This is fine β€” the object itself changed
// user = { name: "Charlie" }; // Error β€” can't reassign

var

The old way (pre-ES6). Function-scoped, not block-scoped. Avoid in modern code:

var age = 30;
age = 31; // Can be reassigned

if (true) {
  var x = 10; // var leaks out of blocks!
}
console.log(x); // β†’ 10 (no error!)
Featureletconstvar
ScopeBlockBlockFunction
ReassignableYesNoYes
HoistingYes (TDZ)Yes (TDZ)Yes
RedeclareNoNoYes

Variable naming rules

  • Must start with a letter, _, or $
  • Can contain letters, digits, _, $
  • Case-sensitive (myVar β‰  myvar)
  • Cannot use reserved words (if, for, class, etc.)
let userName = "Alice";    // camelCase β€” standard convention
let _private = "secret";   // Leading underscore for "private"
let $element = "button";   // jQuery-like convention
let myVariable123 = "ok";  // Digits allowed (not at start)
// let 123abc = "no";      // Error β€” starts with digit
// let let = "no";         // Error β€” reserved word

Data Types

JavaScript has 8 data types. 7 are primitive, 1 is non-primitive (Object).

Primitive Types

// 1. Number
let age = 25;
let price = 19.99;
let infinity = Infinity;
let notANumber = NaN;

// 2. String
let name = "Alice";
let greeting = 'Hello';
let template = `Hi, ${name}!`; // Template literal

// 3. Boolean
let isActive = true;
let isComplete = false;

// 4. Undefined β€” variable declared but no value assigned
let nothing;
console.log(nothing); // β†’ undefined

// 5. Null β€” intentional absence of value
let empty = null;

// 6. Symbol β€” unique identifier (ES6)
let id = Symbol("id");

// 7. BigInt β€” for very large integers (ES2020)
let bigNumber = 9007199254740991n;

typeof operator

Check the type of a value:

typeof 42;         // β†’ "number"
typeof "hello";    // β†’ "string"
typeof true;       // β†’ "boolean"
typeof undefined;  // β†’ "undefined"
typeof null;       // β†’ "object"  ← historical bug!
typeof Symbol();   // β†’ "symbol"
typeof 42n;        // β†’ "bigint"
typeof {};         // β†’ "object"
typeof [];         // β†’ "object"
typeof function(){}; // β†’ "function"

Interaction: alert, prompt, confirm

These are browser-specific functions for interacting with the user:

Demo: User Interaction
JavaScript
let name = prompt('What is your name?', 'Guest');
let confirmed = confirm('Are you sure?');
document.write('<p>Hello, ' + name + '!</p>');
document.write('<p>Confirmed: ' + confirmed + '</p>');
Live Output Window
alert("Hello!");           // Shows a message
let name = prompt("Name?"); // Asks for input (returns string or null)
let ok = confirm("Sure?");  // Asks yes/no (returns boolean)

Note: In Node.js, alert, prompt, and confirm don’t exist. They are browser APIs.

Type Conversions

JavaScript automatically converts types when needed. You can also convert explicitly.

String Conversion

// Explicit
String(123);       // β†’ "123"
String(true);      // β†’ "true"
String(null);      // β†’ "null"
String(undefined); // β†’ "undefined"

// Implicit β€” happens with + when a string is involved
let value = 123 + ""; // β†’ "123"

Number Conversion

// Explicit
Number("123");      // β†’ 123
Number("12.5");     // β†’ 12.5
Number("abc");      // β†’ NaN
Number(true);       // β†’ 1
Number(false);      // β†’ 0
Number(null);       // β†’ 0
Number(undefined);  // β†’ NaN

// Unary + operator (shorthand)
let str = "42";
let num = +str;     // β†’ 42

// parseInt / parseFloat β€” more forgiving
parseInt("100px");  // β†’ 100
parseFloat("3.14em"); // β†’ 3.14

Boolean Conversion

// Explicit
Boolean(1);         // β†’ true
Boolean(0);         // β†’ false
Boolean("hello");   // β†’ true
Boolean("");        // β†’ false
Boolean(null);      // β†’ false
Boolean(undefined); // β†’ false
Boolean(NaN);       // β†’ false

// Double NOT (shorthand)
!!"hello";          // β†’ true
!!0;                // β†’ false

Falsy values (convert to false):

ValueBoolean
0false
"" (empty string)false
nullfalse
undefinedfalse
NaNfalse
falsefalse

Everything else is truthy.

console.log('String conversions:');
console.log(String(123) + ' (type: ' + typeof String(123) + ')');
console.log('Number conversions:');
console.log(Number('42') + ' (type: ' + typeof Number('42') + ')');
console.log('Boolean conversions:');
console.log(Boolean(1) + ', ' + Boolean(0));
console.log('Parsing:');
console.log(parseInt('100px') + ', ' + parseFloat('3.14em'));