Introduction to JavaScript
JavaScript is a versatile programming language primarily used for web development. This tutorial by freeCodeCamp provides a comprehensive introduction to JavaScript fundamentals for beginners.
1. Getting Started with JavaScript
Running JavaScript
- Browser Integration: All web browsers have built-in JavaScript engines
- Code Editors: You can use various editors like Visual Studio Code, Sublime Text, or Atom
- Online Platforms:
- freeCodeCamp.org's built-in editor
- CodePen.io for interactive coding
- Scrimba.com for interactive learning
Basic Syntax and Comments
- Single-line comments: Use
//
for single line comments - Multi-line comments: Use
/* comment */
for multi-line comments - Purpose: Comments help document code for yourself and others
// This is a single-line comment
/* This is
a multi-line
comment */
2. Variables and Data Types
Variable Declaration
- var: Traditional variable declaration (function-scoped)
- let: Block-scoped variable that can be reassigned
- const: Block-scoped variable that cannot be reassigned
var myName = "John"; // Function-scoped
let age = 25; // Block-scoped
const PI = 3.14159; // Constant (cannot be reassigned)
JavaScript Data Types
- Undefined: A variable that hasn't been assigned a value
- Null: Represents "nothing" or "empty"
- Boolean: true or false values
- String: Text enclosed in quotes ('', "", or ``)
- Number: Numeric values (integers or decimals)
- Symbol: Unique and immutable primitive value
- Object: Collections of key-value pairs
Variable Assignment
- The
=
operator assigns values to variables - Variables can be declared first, then assigned later
- Variables can be reassigned (except constants)
var a; // Declaration
a = 7; // Assignment
var b = 2; // Declaration + assignment
b = a; // Reassignment
3. Basic Operators
Arithmetic Operators
- Addition:
+
- Subtraction:
-
- Multiplication:
*
- Division:
/
- Remainder (modulus):
%
Increment and Decrement
- Increment:
++
(adds 1) - Decrement:
--
(subtracts 1)
var myVar = 87;
myVar++; // Equivalent to myVar = myVar + 1
Compound Assignment
+=
: Add and assign-=
: Subtract and assign*=
: Multiply and assign/=
: Divide and assign
a += 12; // Equivalent to a = a + 12
b -= 15; // Equivalent to b = b - 15
c *= 10; // Equivalent to c = c * 10
4. Working with Strings
String Creation
- Strings can be created with single quotes, double quotes, or backticks
- Each has advantages in different situations
var singleQuotes = 'Single quotes string';
var doubleQuotes = "Double quotes string";
var backticks = `Backtick string`;
Escaping Characters
- Use backslash (
\
) to escape special characters - Common escape sequences:
\"
,\'
,\\
,\n
,\t
,\r
var myStr = "I am a \"double quoted\" string.";
String Concatenation
- Using
+
operator to join strings - Using
+=
to append to strings
var ourStr = "I come first. " + "I come second.";
var myStr = "This is the start. ";
myStr += "This is the end.";
String Properties and Methods
.length
: Property that returns the length of a string- Bracket notation to access characters by index (zero-based)
- Strings are immutable (individual characters cannot be changed)
var firstName = "Ada";
var firstLetter = firstName[0]; // "A"
var nameLength = firstName.length; // 3
5. Arrays
Array Basics
- Arrays store multiple values in a single variable
- Arrays can contain different data types
- Array indices are zero-based
var sandwich = ["peanut butter", "jelly", "bread"];
var myArray = [1, "Hello", true];
Nested Arrays (Multidimensional)
- Arrays can contain other arrays
- Access using multiple bracket notations
var nestedArray = [["Bulls", 23], ["White Sox", 45]];
var data = nestedArray[0][1]; // 23
Array Manipulation
- push(): Add element to end of array
- pop(): Remove element from end of array
- shift(): Remove element from beginning of array
- unshift(): Add element to beginning of array
var arr = [1, 2, 3];
arr.push(4); // arr is now [1, 2, 3, 4]
var popped = arr.pop(); // arr is now [1, 2, 3], popped = 4
arr.unshift(0); // arr is now [0, 1, 2, 3]
var shifted = arr.shift(); // arr is now [1, 2, 3], shifted = 0
6. Functions
Function Basics
- Functions are reusable blocks of code
- They can accept parameters and return values
- Functions help make code more modular and maintainable
function functionName() {
console.log("Hello World");
}
function functionWithArgs(a, b) {
console.log(a + b);
}
functionName(); // Calls the function
functionWithArgs(1, 2); // Outputs 3
Return Values
- Functions can return values using the
return
statement - Functions without a return statement return
undefined
function timesFive(num) {
return num * 5;
}
var answer = timesFive(5); // answer = 25
Scope
- Global Scope: Variables defined outside functions
- Local Scope: Variables defined inside functions
- Local variables take precedence over global variables with the same name
var globalVar = 10; // Global variable
function fun1() {
var localVar = 5; // Local variable
console.log(globalVar); // Can access global variable
}
console.log(localVar); // Error: localVar is not defined
7. Conditional Logic
Boolean Values
- Booleans are
true
orfalse
- Used for decision making in code
If Statements
- Execute code blocks based on conditions
- Can include else, else if branches
function test(condition) {
if (condition) {
return "It was true";
} else {
return "It was false";
}
}
Comparison Operators
- Equality:
==
(value only),===
(value and type) - Inequality:
!=
(value only),!==
(value and type) - Relational:
>
,<
,>=
,<=
3 == '3' // true (checks value only)
3 === '3' // false (checks value and type)
Logical Operators
- AND:
&&
(both conditions must be true) - OR:
||
(at least one condition must be true) - NOT:
!
(negates the boolean value)
if (num > 5 && num < 10) {
return "Yes";
}
Switch Statements
- Tests a value against multiple cases
- More efficient than multiple if/else if statements
switch(val) {
case 1:
return "alpha";
break;
case 2:
return "beta";
break;
default:
return "other";
break;
}
8. Objects
Object Basics
- Store key-value pairs (properties)
- Properties can be accessed via dot or bracket notation
var dog = {
"name": "Rex",
"legs": 4,
"tails": 1
};
var nameValue = dog.name; // Dot notation
var legsValue = dog["legs"]; // Bracket notation
Manipulating Objects
- Add properties:
object.newProp = value
- Update properties:
object.existingProp = newValue
- Delete properties:
delete object.prop
dog.bark = "woof"; // Add new property
dog.name = "Buddy"; // Update property
delete dog.tails; // Delete property
Complex Objects
- Objects can contain arrays and other objects
- Used for more complex data structures
var myMusic = [
{
"artist": "Billy Joel",
"title": "Piano Man",
"release_year": 1973,
"formats": ["CD", "8T", "LP"]
}
];
9. Loops
While Loops
- Runs as long as the condition is true
- Useful when you don't know how many iterations needed
var i = 0;
while (i < 5) {
console.log(i);
i++;
}
For Loops
- More concise syntax for iterations
- Preferred when number of iterations is known
for (var i = 0; i < 5; i++) {
console.log(i);
}
Do...While Loops
- Similar to while, but executes at least once
var i = 0;
do {
console.log(i);
i++;
} while (i < 5);
10. ES6 Features
let and const
let
: Block-scoped variable declarationconst
: Block-scoped constant declaration
// let is limited to the block
if (true) {
let i = 5;
}
console.log(i); // Error: i is not defined
// const cannot be reassigned
const PI = 3.14;
PI = 3.15; // Error: Assignment to constant variable
Arrow Functions
- Shorter syntax for function expressions
- Lexical
this
binding
// Traditional function
var multiply = function(a, b) {
return a * b;
};
// Arrow function
const multiply = (a, b) => a * b;
Destructuring Assignment
- Extract values from arrays or objects
// Array destructuring
const [a, b] = [1, 2];
// Object destructuring
const { name, age } = { name: 'John', age: 30 };
Template Literals
- String interpolation using backticks
- Multi-line strings without escape characters
const name = 'John';
const greeting = `Hello, ${name}!
How are you today?`;
Classes
- Syntactic sugar over JavaScript's prototype-based inheritance
- Cleaner, more familiar syntax for OOP
class Rectangle {
constructor(height, width) {
this.height = height;
this.width = width;
}
get area() {
return this.height * this.width;
}
}
Modules (import/export)
- Share code between JavaScript files
- Organize code into self-contained, reusable pieces
// In one file
export const add = (a, b) => a + b;
// In another file
import { add } from './math.js';
Learning Strategy for JavaScript
According to the instructor, the best approach to mastering JavaScript is:
- Active Coding: Practice each concept as you learn it
- Complete Interactive Challenges: Use the freeCodeCamp curriculum
- Build Projects: Apply knowledge by creating your own JavaScript projects
- Independent Problem-Solving: Use search engines to find solutions when stuck
- Review Fundamentals: Regularly revisit basic concepts even as you advance
Practical Applications and Projects
- Beginner Projects: Passenger counter app, calculator, blackjack game
- Intermediate Projects: Chrome extensions, e-commerce features
- Advanced Projects: Full web applications with JavaScript frameworks
Tools for JavaScript Learning
- Browser Console: For quick testing and experimentation
- Code Editors: VS Code, Sublime Text, or Atom
- Online Platforms:
- freeCodeCamp.org - Interactive curriculum
- CodePen.io - Online editor for web development
- Scrimba.com - Interactive learning platform
Summary
This comprehensive JavaScript course covers all fundamental concepts needed to start building real applications.