Podcast
Questions and Answers
What is JavaScript primarily used for?
What is JavaScript primarily used for?
- Server-side scripting only
- Database management
- Creating operating systems
- Client-side scripting to enhance web page interactivity (correct)
Which of the following is a core capability of JavaScript?
Which of the following is a core capability of JavaScript?
- Data encryption
- Creating 3D models
- Language Basics - syntax, keywords, operators and built-in objects (correct)
- Managing server infrastructure
In HTML, where is it best practice to include JavaScript?
In HTML, where is it best practice to include JavaScript?
- Within the `<head>` section
- At the beginning of the `<body>` section
- Inside a CSS file
- At the end of the `<body>` section (correct)
Which of the following is a use of console.log()
in JavaScript?
Which of the following is a use of console.log()
in JavaScript?
What does the term 'hoisting' refer to in JavaScript?
What does the term 'hoisting' refer to in JavaScript?
Flashcards
What is JavaScript?
What is JavaScript?
An object-based scripting language embedded in web browsers that enables client-side scripting, improving web page responsiveness.
Keywords (in JS)
Keywords (in JS)
Words that have special significance in the JavaScript language.
Operators (in JS)
Operators (in JS)
Special characters that perform an operation on one or more operands.
Expressions (in JS)
Expressions (in JS)
Signup and view all the flashcards
Number Literals
Number Literals
Signup and view all the flashcards
Study Notes
Basics of JavaScript
- JavaScript is an object-based scripting language
- It is embedded in web browsers like Chrome, Edge, and Firefox
- It enables client-side scripting
- This enhances web page responsiveness
- Brendan Eich created JavaScript at Netscape in 1995
- It was originally named LiveScript, then renamed to align with Java's popularity; however, it's unrelated to Java
- Before JavaScript, web pages used server-side scripts, leading to slower response times
- JavaScript allows faster and more interactive web experiences directly in the browser
JavaScript Evolution & Key Features
- Microsoft introduced JScript, which led to fragmentation concerns
- In 1997, JavaScript was standardized as ECMAScript by Ecma International
- It is still commonly referred to as JavaScript, despite the official name
- Brendan Eich co-founded Mozilla and helped launch Firefox.
- Core capabilities include language basics (syntax, keywords, operators, and built-in objects)
- Core capabilities include web page interaction through DOM manipulation and dynamic content.
- Core capabilities include web applications by creating responsive web apps and handling JSON data
Including Scripts
- JavaScript code is included in HTML documents between
<script>
tags - JavaScript can dynamically write content into an HTML element using the
innerText
property with a specified id - JavaScript can display output using a pop-up alert
- The
alert()
method of the window object to display content in a dialog box
Inline JavaScript
- It must be inserted between the
<script>
tags - Example:
document.getElementById( 'message' ).innerText = 'Hello World!'
- JavaScript can be placed in the follow locations inside an HTML document
- In the
<head>
section, though it's not recommended for large scripts - Inside the
<body>
section which can slow down page rendering - At the end of the
<body>
section, which is the best practice because it ensures the page loads before scripts run
External JavaScript
- JavaScript code can be written in external
.js
files To include external JavaScript files, the tag is used with thesrc
attribute:
- External JavaScript files promote reusability, better organization, and easier maintenance
- Only JavaScript code is written in the
.js
file, not<script>
tags
Console Output
- JavaScript can display output using a pop-up alert
- This calls the
alert()
method of the window object in a dialog box
window.alert('Hello World!');
- Debugging can be done using the
log()
method of the console object to display content in the browser's JavaScript console
console.log('Hello World!');
Making Statements
- JavaScript code has a series of instructions called "statements"
- They are generally executed in top-to-bottom order by the browser's JavaScript engine
- Statements contain;
- Keywords: Words with special significance in JavaScript
- Operators: Characters performing operations on operands
- Values: Text strings, numbers, booleans, undefined, and null
- Expressions: Code units that produce a single value
JavaScript Statement Termination & Readability
- Earlier JavaScript required semicolons (;) at the end of statements
- Semicolons are now optional unless multiple statements are on the same line
- Some developers still prefer semicolons for clarity
- JavaScript ignores extra spaces, tabs and line breaks
- Spacing improves readability
- Use the space bar to indent statements
- Tab spacing may render differently in text editors
Expressions vs Statements
Term | Definition | Example |
---|---|---|
Expression | Produces a value, used in calculations | (80 + 20) |
Statement | Performs an action like declaring variables | let total=300 |
JavaScript Statements & Syntax
- "Syntax" is the rules governing the JavaScript language
- JavaScript statements are often grouped using curly brackets
{}
inside function blocks - Blocks allows for reusable execution when required.
- good practice to indent statements by two spaces for better readability
JavaScript is Case Sensitive
- Variables
total
andTotal
are different - Comments help explain code for better readability and debugging
- Single-line comments
//
are used for short explanations Multi-line comments/*...*/
are used for longer explanations - Comments helps explain complex logic
Fixed Values (Literals)
- Number literals include integer e.g.(100) or floating-point numbers e.g.(3.142)
- String literals are text in single e.g. ('JavaScript Fun') or double quotes e.g.("JavaScript Fun")
- Consistency is important when using string literals by Using either 'single' or "double" quotes
Variable Values (Variables)
- "Variables" store data within a script
- They are created using the JavaScript
let
keyword - For example,
let total
creates a variable named “total” - Variables are assigned a value using the JavaScript
=
assignment operator
Expressions and Operators
- Expressions produces a single value
- This is done by combining values and operators
- example:
let result = (80 + 20);
- Numeric Expressions includes variables: example
let total = 300;
- Operators are used in expressions: example;
let finalValue = (100 + 50) * 2; // 300
Adding Comments in JavaScript
//
indicates single line comments, typically for a short explanation./*…*/
indicates multi-line comments, typically for longer explanations, or disabling blocks of code- Good practice to Always use comments to explain complex logic
- 'Comment out' lines of code that prevent their execution for debugging
Variables
- Variables are containers common to every scripting and programming language where data can be stored and retrieved later.
- JavaScript variables are easier to use because they are loosely typed by any type of data
Loosely vs Strongly Typed Variables
Type | Description | Example Language |
---|---|---|
Strongly Typed | Must declare a specific data type before use | Java, C++, C# |
Loosely Typed | Can store any data type without prior declaration Example Typed Variable Type | JavaScript |
int age = 25; // Can ONLY store integers
example of Strongly Typed Variablelet data = 25; // Can Store any type of data
example of Loosely Typed Variable- JavaScript variables can be declared in 4 ways:
- Automatically
- Using
var
- Using
let
- Using
const
Automatically declaring variables
- In this first example,
x
,y
, andz
are undeclared variables. - They are automatically declared when first used.
- It is good programming practice to always declare variables before use.
Using var
- The
var
keyword was used in all JavaScript code from 1995 to 2015. - The
var
keyword should only be used in code written for older browsers.
Using let
- The
let
andconst
keywords were added to JavaScript in 2015. - Variables declared with
let
can be reassigned new values as the script proceeds Alet
variable can be declared without a value and assigned later. - With let, Multiple variables may be declared on a single line
- ex:
let i,j,k; or let i = 10, j = 20
Using const
const
is constant values and cannot be changed- Use
const
if the type should not be changed (Arrays and Objects)
The typeOf keyword
- Choose meaningful names for your variables to make the script easier to understand later
- JavaScript automatically sets the variable type for the value assigned.
- Subsequent assignation of a different data type later in the script can be made to change the variable type.
- The current variable type can be revealed by the
typeof
keyword
Creating Functions
- A JavaScript function is a block of code designed to perform a particular task, and it returns a final single value.
- A JavaScript function is executed when "something" invokes it (calls it).
JavaScript Function Syntax
- JavaScript functions use the
function
keyword, function name, and parenthesis to define. - Function names can contain letters, digits, underscores, and dollar signs.
- Parentheses may include parameter names separated by commas
- Code is placed inside curly brackets
- Arguments are the values received when invoked
- Inside the function, arguments behave as local variables
Function Invocation
- When an event happens such as; a user clicks a button
- When it is invoked (called) from JavaScript code
- Automatically (self invoked)
Function Return
- Functions stop exectuting on the
return statement
- If a function was invoked from a statement, JavaScript will "return" after invoking
- Functions often compute and 'return' the value back to the "caller"
Assigning Functions to Variables
- Functions are assigned to Variables
function add(num1, num2) {
return num1 + num2
}
let addition = add
console.log(“Result:“, addition(100,200))
- Anonymous Functions (Function Expressions) has the format:
let anon = function(num1, num2) {
return num1 + num2
}
Self-Invoking Functions
- Self-invoking functions are used widely to execute example code when the script gets loaded.
(function add(num1, num2) {
return num1 + num2
})()
Function Hoisting
- Function Declarations can be called before they are defined
console.log("Volvo“, add(100,200))
function add(num1, num2) {
return num1 + num2
}
However, function expressions are not hoisted
console.log("Volvo“, add(100,200))
let x = function add(num1, num2) {
return num1 + num2
}
Recognizing Scope
- Scope determines where a variable is accessible in a script.
- JavaScript uses lexical scope, the variable's environment determines accessibility.
- The 2 main types of scope are:
- Global Scope
- Local Scope
Global Scope
- A global variable is declared outside any function
- It is accessible throughout the entire script
- One potential issue in that script naming conflicts will arise with external scripts
Local Scope
- A local variable is declared inside a function
- It only exists inside this function and cannot be accessed outside
Converting Values
- JavaScript handles data types differently, converting is important to prevent errors
JavaScript Conversion Importance
- Mixed data types (e.g., strings and numbers) can lead to unexpected results
- converting a string or other types to numbers allows for proper mathematical operations
Example of UnExpected Behaviour
-
'42' + 8
results in'428'
(string concatenation, not addition). -
The value
'42'
is a string, but8
is a number. -
In JavaScript, strings can be converted to numbers using built-in functions like
parseInt()
andparseFloat()
\ -
These functions allow working with numeric types
Conversion Functions
- parseInt()
- Converts a string to an integer (whole number). Ex: parseInt('42') converts to 42
- parseInt("42nd Street") converts to 42
- parseFloat() Converts a string to a floating-point number like,
parseFloat('42.5px')
which converted to42.5
Built-in Functions for Conversion
- Strings to numbers for conversion functions in Javascript
parseInt();
parseFloat();
- JavaScript returns
NaN
(Not a Number) when the conversion fails - ex:
parseInt('Hello')
toNaN
isNaN(value)
returnstrue
if the value is not a number
String()
- Converts a number to a string. Example
String(42)
to'42'
toString()
Converts a number to a string with ex:num.toString()
to'42'
Arithmetic
- Arithmetical operators are used in JavaScript
Operator | Operation |
---|---|
+ | Addition/Concatenation of strings |
- | Subtraction |
* | Multiplication |
/ | Division |
% | Modulus (remainder) |
++ | Increment |
-- | Decrement |
** | Exponentiation |
Assignment Operators
- Assignment operators perform an operation and assign the result in a single step
Operator | Example | Equivalent |
---|---|---|
= | a = b | a = b |
+= | a += b | a = (a + b) |
-= | a -= b | a = (a - b) |
*= | a *= b | a = (a * b) |
/= | a /= b | a = (a /b) |
%= | a %= b | a = (a % b) |
**= | a **= b | a = (a ** b) |
Comparisons
- Comparison operators are used to evaluate conditions between 2 values
- The equality operators check both value and data type.
- Relational operators like >, <, >=, and = and
{}
curly bracket function blocks - Variables and function names contain letters, numbers, underscores (no keywords)
- Variables contain data types of String, Number, Boolean, Object, Function, Symbol, null, and undefined
- Variables with
let
can reassign values (butconst
cannot) - Functions are grouped in
{}
execution returns a value - () parentheses, expressions can contain variable args
- ( ) parentheses operator calls the function
- Hoisting to call functions before declarations in the script
- Anonymous function expressions have no name
- Lexical scope creates environment, local (global closure)
Studying That Suits You
Use AI to generate personalized quizzes and flashcards to suit your learning preferences.