Getting Started with JavaScript
Ways to Run JavaScript
1. Online Tools
- Codepen: https://codepen.io/
- JSfiddle: https://jsfiddle.net/
- JSbin: https://jsbin.com/?js,console
- OneCompiler: https://onecompiler.com/javascript
2. Command Line (Node.js)
- Install Node.js: https://nodejs.org/en/download/
- NodeJS is a "JavaScript runtime environment" = an environment where you can execute JavaScript code locally (without a browser)
- Editing code can be done via Visual Studio Code (!= Visual Studio)
- Steps:
- Open a new folder in VS Code
- Create a new file:
index.js - Add code (e.g.,
console.log('Hello world')) - Open the VS Code terminal (CTRL+T / CMD+T)
- Enter:
node index.js
3. On a Website
- The most common way to use JavaScript
- JavaScript code via a website is executed by your browser
- Making major errors in JavaScript (e.g., infinite loops) can cause your computer to crash
- JavaScript is not compiled, so no one will discover errors for you
- Work through a local website using:
- HTML file with
<script>tags - VS Code with Live Server extension (for auto-reload)
- Use Emmet for basic HTML (type
!then<tab>)
- HTML file with
Development Tools
IDEs (Integrated Development Environments):
- Visual Studio Code: https://code.visualstudio.com/
- Sublime Text: https://www.sublimetext.com/
- WebStorm: https://www.jetbrains.com/webstorm/
- Brackets: https://brackets.io/
VS Code Extensions:
- Live Server (by Ritwick Dey) - for local development with auto-reload
Outputting Text
console.log(): Write text to the console log (used for "debugging")
- Find the console in Chrome's Developer Toolbar
- Access via: Right-click → Inspect → Console tab
document.write(): Write text to a page (will only work when there is an HTML page)
JavaScript Basics
Comments
// This is 1 line of comment
/*
* These are multiple lines of comments
*/
Variables
Declaration
- JavaScript is dynamically-typed; you don't specify a type for variables (no int, string, etc.)
- JavaScript determines the type itself
- Declare variables using
varorletorconst
var vs let
var: Declares a variable in the "global" scopelet: Declares a variable in a "local" scope
let a = 1;
if (true) {
var b = 2; // Accessible outside the block
let c = 3; // Only accessible inside the block
}
console.log(a); // outputs 1
console.log(b); // outputs 2
console.log(c); // ReferenceError: c is not defined
const
- Constant, cannot be changed after declaration
- Use for values that should not be reassigned
const myCat = 'Minnie';
// myCat = 'Max'; // Error: Assignment to constant variable
Variable Behavior
- Variables that have not yet been defined are "undefined"
- If you do "strange" things with variables, you get NaN (Not a Number)
- Variables in JavaScript can change type
let x;
console.log(x); // undefined
x = 1;
console.log(x); // 1
let result = "hello" * 2;
console.log(result); // NaN
let number = 5;
console.log(typeof number); // "number"
number = "Hello";
console.log(typeof number); // "string"
Type Checking
Use typeof to check the type of a variable
let name = "John";
console.log(typeof name); // outputs "string"
name = 42;
console.log(typeof name); // outputs "number"
Type Conversion
You can "force" the type of a variable yourself
let number = 5;
number = String(number); // Convert to string
console.log(typeof number); // "string"
let text = "Hello";
text = Number(text); // Convert to number (results in NaN if not a valid number)
console.log(typeof text); // "number"
Using Variables in Strings
Concatenation
const myCat = 'Minnie';
console.log('The name of my cat is ' + myCat);
Template Literals (Backticks and ${})
const myCat = 'Minnie';
console.log(`The name of my cat is ${myCat}`);
Operators
Comparison Operators
<,>,<=,>=,==,!=- Compare contents===,!==- Compare contents AND type
const x = "5";
const y = 5;
console.log(x == y); // Output: true (compares values)
console.log(x === y); // Output: false (compares values and types)
Logical Operators
&&(AND)||(OR)
Programming in JavaScript
Conditionals
if/else if/else
let number = 5;
if(number === 5) {
console.log('The number is 5');
} else if(number > 5) {
console.log('The number is bigger than 5');
} else {
console.log('The number is smaller than 5');
}
Ternary Operator (Short if)
let number = 5;
console.log(number === 5 ? true : false);
switch Statement
let text = 'abc';
switch(text) {
case 'abc':
console.log('It starts with...');
break;
case 'def':
console.log('And then...');
break;
default:
console.log('I\'m done with this game');
}
Functions
Function Declaration
function greetWorld() {
console.log('Hello world!');
}
greetWorld();
Function with Parameters
function greetCountry(country) {
console.log('Hello ' + country);
}
greetCountry('Belgium');
Function with Return
function greetCountry(country) {
if (typeof country === 'undefined' || country === '') {
return 'Hello World';
} else {
return 'Hello ' + country;
}
}
let greeting = greetCountry('Belgium');
console.log(greeting);
Function with Default Parameters
function greetCountry(country = '') {
if (country === '') {
return 'Hello World';
} else {
return 'Hello ' + country;
}
}
let greeting = greetCountry('Belgium');
console.log(greeting);
Anonymous Functions
// Anonymous functions
let callable = function() {
return '123';
}
Arrow Functions
// Arrow functions
const greetWorld = (country = 'World') => {
return 'Hello ' + country;
};
// Arrow functions with a single parameter (and no default values)
const print = text => {
console.log(text);
};
Note: Anonymous functions are used when you don't need to reuse the function elsewhere. You'll see these a lot in JavaScript for callbacks, event handlers, etc.
Loops
while Loop
let i = 0;
while (i < 5) {
console.log(i);
i++;
}
do...while Loop
let x = 0;
let i = 0;
do {
x = x + i;
console.log(x);
i++;
} while (i < 5);
for Loop
let i;
for (i = 0; i < 4; i++) {
console.log(i);
}
forEach Loop (Array Method)
const numbers = [28, 77, 45, 99, 27];
numbers.forEach(function(number) {
console.log(number);
});
// With arrow function
numbers.forEach(number => {
console.log(number);
});
filter (Array Method)
const randomNumbers = [4, 11, 42, 14, 39];
const filteredArray = randomNumbers.filter(n => {
return n > 5;
});
console.log(filteredArray);
Note: filter returns true or false and based on that it retains the value
map (Array Method)
const finalParticipants = ['Taylor', 'Donald', 'Don', 'Natasha', 'Bobby'];
// add string after each final participant
const announcements = finalParticipants.map(member => {
return member + ' joined the contest.';
});
console.log(announcements);
Note: map transforms the content through the return value
Arrays
Declaration and Access
// An array containing numbers
const numberArray = [0, 1, 2, 3];
// An array containing different data types
const mixedArray = [1, 'chicken', false];
// Accessing elements
const myArray = [100, 200, 300];
console.log(myArray[0]); // 100
console.log(myArray[1]); // 200
console.log(myArray[2]); // 300
// Length property
const numbers = [1, 2, 3, 4];
console.log(numbers.length); // 4
Objects
Object Literals
const apple = {
color: 'Green',
price: {
bulk: '$3/kg',
smallQty: '$4/kg'
}
};
console.log(apple.color); // 'Green'
console.log(apple.price.bulk); // '$3/kg'
// Modify properties
apple.color = 'Blue';
console.log(apple.color); // 'Blue'
Adding and Deleting Properties
const student = {
name: 'Sheldon',
score: 100,
grade: 'A',
};
console.log(student);
delete student.score; // Delete property
student.grade = 'F'; // Modify property
console.log(student);
Iterating Over Objects (for...in)
let mobile = {
brand: 'Samsung',
model: 'Galaxy Note 9'
};
for (let key in mobile) {
console.log(`${key}: ${mobile[key]}`);
}
Object Methods
const engine = {
// method shorthand, with one argument
start(adverb) {
console.log(`The engine starts up ${adverb}...`);
},
// anonymous arrow function expression with no arguments
sputter() {
console.log('The engine sputters...');
},
};
engine.start('noisily');
engine.sputter();
this Keyword
const cat = {
name: 'Pipey',
age: 8,
whatName() {
return this.name;
}
};
console.log(cat.whatName()); // 'Pipey'
User Input: prompt()
let answer = prompt('What is your name?');
console.log(answer);
Important Note: A prompt input is always text/string, so if you want to use it as a number, it's best to use Number(answer) or parseInt(answer) with your result.
JavaScript and HTML Integration
Separation of Concerns
Bad Practice (Inline JavaScript)
<html>
<body>
<script>
document.write('Hello world');
</script>
</body>
</html>
Disadvantages:
- Not clear / structured
- Not the standard
- No "Separation of concerns"
Good Practice (External JavaScript)
<html>
<body>
<script src="app.js"></script>
</body>
</html>
In app.js:
document.write('Hello World');
Benefits:
- Easier to manage, more organized
- W3C Standard
- "Separation of concerns"
- Caching
- Reusability
External Scripts (CDN)
<html>
<body>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
</body>
</html>
Browser Object Model (BOM)
The Browser Object Model (BOM) is a collection of objects that give you access to the browser and computer screen.
Reference: https://www.w3schools.com/js/js_window.asp
Window Object
The window object is a global object in JavaScript that represents your browser window or frame. It has numerous methods that you can use to control or manipulate the window.
console.log(window); // See all properties and methods of window
window.alert()
window.alert('Hello world');
// Also possible without window.
alert('Hello world');
window.prompt()
window.prompt('What is your name?');
// Also possible without window.
prompt('What is your name?');
// Store the result
let yourName = prompt('What is your name?');
// With default value
let yourName = prompt('What is your name?', 'Joske');
window.confirm()
if (window.confirm("Do you like kittens?")) {
console.log("You like kittens!");
} else {
console.log("You don't like kittens!");
}
// You can also use it without window
if (confirm("Do you like kittens?")) {
console.log("You like kittens!");
}
window.innerWidth and window.innerHeight
document.write('Window width: ' + window.innerWidth + '<br />');
document.write('Window height: ' + window.innerHeight + '<br />');
window.open()
window.open('https://www.google.com', '_blank');
// With options
window.open(
'https://www.google.com',
'_blank',
'width=200,height=100'
);
window.location
window.location = 'https://www.google.com';
window.setTimeout()
setTimeout(function() {
console.log('This runs after 2 seconds');
}, 2000);
window.navigator
console.log(navigator.userAgent);
window.screen
document.write("Viewport width: " + window.innerWidth + '<br>');
document.write("Screen width: " + screen.width + '<br>');
window.print()
window.print();
Key Concepts Summary
Data Types
- String, Number, Boolean, Arrays, Objects, undefined, NaN
Control Structures
if/else if/elseswitchstatements- Ternary operator (
? :)
Loops
while,do...while,forforEach,filter,map(array methods)
Functions
- Function declarations
- Parameters and return values
- Anonymous functions
- Arrow functions
- Default parameters
Arrays
- Declaration:
const arr = [1, 2, 3] - Access:
arr[0] - Length:
arr.length - Can contain mixed data types
Objects
- Object literals:
{ key: value } - Access properties:
obj.keyorobj['key'] - Nested objects
- Methods: functions as object properties
thiskeywordfor...inloop
Browser Integration
- External JavaScript files:
<script src="app.js"></script> - Separation of concerns
- Browser Object Model (BOM)
- Window object and its methods
Important Notes
- JavaScript is dynamically-typed
- Variables can change type
- Use
typeofto check types - Use
Number()orparseInt()to convert strings to numbers - Use
String()to convert to strings prompt()always returns a string- Always work with external JavaScript files in exercises