JavaScript
03-10-2023 Sat
Learning to code:
- opens new doors
- creates new hobbies
- launches new careers
- develops new skills
- expands your network
Functions
If Statements
Loops
Math Operators
Assignment Operators
Comparison Operators
Logical Operators
Variables
Every programming language has its own built-in data types.
In JavaScript, numbers can be whole (such as 10) or contain a decimal (such as 10.5).
EXAMPLE:
The numberOfApples
and temperature
variables both store numbers.
Strings store text, such as letters, words, symbols, and spaces.
EXAMPLE:
The message
variable stores the string 'Hello world'
.
A boolean stores the value true or false.
EXAMPLE:
It’s true that you’re learning to code, but it’s false that sandals should be worn with socks.
An array is a list containing multiple items. The items can be different data types: numbers, strings, and even other arrays. An array inside another array is called a nested array.
EXAMPLE:
exampleArray
has 5 items. It contains strings, numbers and an array; which itself has two items that are numbers.
Array Indexing
Array indexing provides a way to access a specific item in an array.
The fruit
variable holds the third item in the array, 'oranges'
.
Object
An object stores an unordered list of properties.
EXAMPLE:
variety
and pricePerPound
are properties of the apple
object.
'red'
is the value stored in the variety
property.
1.25
is the value stored in the pricePerPound
property.
Dot notation is one way to access a property of an object. To use dot notation, write the name of the object, followed by a dot (.), followed by the name of the property.
EXAMPLE:
This code will print the name
property of the cat
object, 'Moo'
.
Bracket notation is another way to access a property of an object.
EXAMPLE:
This code will print the name
property of the dog
object, 'Lady'
.
When a variable has not been assigned a value, its value is undefined.
EXAMPLE:
The fruit
variable doesn’t have a value so this code will print undefined
.
Functions
A function is a reusable block of code that tells a computer to do a specific thing. Functions usually take information, process it, and return a result.
When you call a function, you’re telling the computer to run a specific block of code.
An argument is extra information given to a function that tells it how it should run.
EXAMPLE:
The sayHello()
function call tells the computer to run the sayHello
function. It doesn’t take any arguments.
The printSum(1,2)
function call tells the computer to run the printSum
function using the numbers 1
and 2
as the necessary arguments.
A function declaration is used to create a function.
- The name of the function
- Optional parameters ( ) that behave like variables inside the function. Parameters tell the function what to do with the arguments it’s given.
- The block of code {} to run when the function is called.
EXAMPLE:
The addNumbers
function adds 2 numbers together and then returns the result.
When a function is used as an argument to another function, it’s called a callback function. You can tell a function is a callback when it doesn’t have parentheses after its name.
EXAMPLE:
The array method .forEach()
takes the callback function print()
as an argument, and will apply that function to each item in the array.
An arrow function is a compact way to write a function declaration.
EXAMPLE:
Here is an example of a function that takes 2 numbers and adds them together; and the same code using an arrow function.
Array Methods - Learning different ways to search arrays, combine elements, transform elements, using arrow functions.
Use a classic for loop to iterate over every other element in an array.
Classic For Loop
In JavaScript, a classic for loop repeats the same code inside the blook { } a specified number of times. It is defined in three parts.
The first part happens before the loop starts and defines a looping variable
The second part is a test that determines if the loop should keep repeating
(i < 10;).
And The third part updates the looping variable each time the loop repeats.
(i = i + 1).
Example code
print('The loop will go as long for
(var i = 0; i < 10;
i = i + print(i);
}
:::::::::::::::::
In this example, the looping variable (i) starts at 0. The code in the block { } will keep repeating while i is less than 10. And i is increased by 1 each loop. The code prints out the message, the loop will go as long as i is less than 10.", and then it prints the numbers 0 through 9
In this lab I will use the classic for loop to iterate over every other element in an array.
A Classic For Loop has 3 parts.
1. A start position that declares a variable and gives it a value.
2. A test that keeps a classic for loop running as long as long as the test is true.
3. An update operation that changes the variable after each iteration.
The closingTimes array contains a list of times as strings. Update every other element in the array with a classic for loop.
Instructions:
* Inside the setup ( ) of the classic for loop,
change the
i += 1 to i += 2
* inside the code block { }, change 5 pm to "9pm"
My Code
Import {closingTimes} from' grasshoper.store' ;
console.log (closingTimes);
for (let i = 0; i < closingTimes
.length; i += 1) {
closingTimes [i] = '5pm'
:::::::::::::::
Use the indexOf method to
find the indedex number of your favorite cereal 🥣
ç==============è
A Milk Mistake
The lastIndexOf method is similar to indexOf,
but searches
in reverse from end of an array.
If no
element is found. .lastIndexOf will return – 1.
When
checking g out of the grocery store, milk was accidentally scanned twice. Find
the index of the second milk 🥛
using lastIndexOf( )
Instructions:
Inside parentheses .lastIndexOf(
):
Ø Add milk as a argument.
import { cart } from '
grasshopper.store' ;
console.log( cart ) ;
let index = cart .lastIndexOf ( '
eggs
' )
console.log (
'
The extra item is at index : ‘ +
Index ) ‘
let index = cart .lastIndexOf ( 'milk' )
Sample Code Results:
>> flour, milk,
milk, eggs
>> flour, milk,
milk, eggs
My Code Results :
>> flour, milk,
milk, eggs
>> The extra
ingredient is at index: 2
Congrats!
You used a lastIndexOf ( ) array method to find
the last index element in an array.
03-27-2023 Web 18:00
- editing and
- testing your javascript code snippets.
- CodePen or
- JSFiddle.
- The javascript tester will
- highlight syntax errors in the editor and
- provide meaningful messages to
- help debug your code.
- Runtime errors are shown below the editor.
Result of evaluating code:
["Fido","Bowser","Rusty"]
::::::::::::::::::::::::::::::::::::::::
var dog = {
name: 'Lady',
friends: ['Moo','Bowie'],
};
console.log(dog['name'])
Result of evaluating code:
"Lady"
undefined
The tester will evaluate your code and print the result to result section under the editor. The basic idea is you enter snippets of code you want to test with. The last expression will get printed as a result. The last expression should not contain a "return" statement or a variable assignment. It should just be an expression. You can also add additional console.log messages at various points in you code and these will also be shown in the result section on this page.
For example:
const dogs = [
{age: 10, name: 'Fido'},
{age: 14, name: 'Bowser'},
{age: 16, name: 'Rusty'}
];
dogs.map(dog => dog.name);
Try adding the following before the last statement and then click Run again:console.log(dogs.map(dog => {return {name: dog.name}}));
Great for testing ideas or running simple code snippets...
This editor works entirely in your browser (it uses the Ace embeddable code editor.). Your code is not sent to any server. If you close the browser or tab the current state of the editor is saved. If you don't want your code saved remember to clear the editor before closing. We value Privacy!
See below for keyboard shortcuts
JavaScript Tester - Features
- Tokenization: Breaking text into a list of tokens
- Theming: Using themes or user settings to map the tokens to specific colors and styles
Tokenization#
The tokenization of text is about breaking the text into segments and to classify each segment with a token type.
VS Code's tokenization engine is powered by TextMate grammars. TextMate grammars are a structured collection of regular expressions and are written as a plist (XML) or JSON files. VS Code extensions can contribute grammars through the grammars
contribution point.
The TextMate tokenization engine runs in the same process as the renderer and tokens are updated as the user types. Tokens are used for syntax highlighting, but also to classify the source code into areas of comments, strings, regex.
Starting with release 1.43, VS Code also allows extensions to provide tokenization through a Semantic Token Provider. Semantic providers are typically implemented by language servers that have a deeper understanding of the source file and can resolve symbols in the context of the project. For example, a constant variable name can be rendered using constant highlighting throughout the project, not just at the place of its declaration.
Highlighting based on semantic tokens is considered an addition to the TextMate-based syntax highlighting. Semantic highlighting goes on top of the syntax highlighting. And as language servers can take a while to load and analyze a project, semantic token highlighting may appear after a short delay.
Indenting syntax
Last Updated: 2021-03-22
You can indent or outdent selected lines of syntax and you can automatically indent selections so that the syntax is formatted in a manner similar to syntax pasted from a dialog box.
- The default indent is four spaces and applies to indenting selected lines of syntax as well as to automatic indentation. You can change the indent size from the Syntax Editor tab in the Options dialog box.
- Note that using the Tab key in the Syntax Editor does not insert a tab character. It inserts a space.
Indenting text
- Select the text or position the cursor on a single line that you want to indent.
- From the menus choose:
You can also indent a selection or line by pressing the Tab key.
Outdenting text
- Select the text or position the cursor on a single line that you want to outdent.
- From the menus choose:
Automatically indenting text
- Select the text.
- From the menus choose:
When you automatically indent text, any existing indentation is removed and replaced with the automatically generated indents. Note that automatically indenting code within a BEGIN PROGRAM block may break the code if it depends on specific indentation to function, such as Python code containing loops and conditional blocks.
Syntax formatted with the auto-indent feature may not run in batch mode. For example, auto-indenting an INPUT PROGRAM-END INPUT PROGRAM, LOOP-END LOOP, DO IF-END IF or DO REPEAT-END REPEAT block will cause the syntax to fail in batch mode because commands in the block will be indented and will not start in column 1 as required for batch mode. You can, however, use the -i switch in batch mode to force the Batch Facility to use interactive syntax rules. See the topic Syntax Rules for more information.
Handles large documents
Search and replace with regular expressions (Ctrl-F)
Highlight matching parentheses
Drag and drop text using the mouse
Line wrapping
Code folding
Multiple cursors and selections
Cut, copy, and paste functionality
The following video gives some color theory basics to help you with your selections.
Semantic Highlight Guide
Semantic highlighting is an addition to syntax highlighting as described in the Syntax Highlight guide. Visual Studio Code uses TextMate grammars as the main tokenization engine. TextMate grammars work on a single file as input and break it up based on lexical rules expressed in regular expressions.
Semantic tokenization allows language servers to provide additional token information based on the language server's knowledge on how to resolve symbols in the context of a project. Themes can opt in to use semantic tokens to improve and refine the syntax highlighting from grammars. The editor applies the highlighting from semantic tokens on top of the highlighting from grammars.
Here's an example of what semantic highlighting can add:
Without semantic highlighting:
With semantic highlighting:
Notice the color differences based on language service symbol understanding:
- line 10:
languageModes
is colored as a parameter - line 11:
Range
andPosition
are colored as classes anddocument
as a parameter. - line 13:
getFoldingRanges
is colored as a function
Editor Keyboard Shortcuts
Line Operations:
Windows/Linux Mac Action
Ctrl-D Command-D Remove line
Alt-Shift-Down Command-Option-Down Copy lines down
Alt-Shift-Up Command-Option-Up Copy lines up
Alt-Down Option-Down Move lines down
Alt-Up Option-Up Move lines up
Alt-Delete Ctrl-K Remove to line end
Alt-Backspace Command-Backspace Remove to linestart
Ctrl-Backspace Option-Backspace, Ctrl-Option-Backspace Remove word left
Ctrl-Delete Option-Delete Remove word right
Selection
Windows/Linux | Mac | Action |
---|---|---|
Ctrl-A | Command-A | Select all |
Shift-Left | Shift-Left | Select left |
Shift-Right | Shift-Right | Select right |
Ctrl-Shift-Left | Option-Shift-Left | Select word left |
Ctrl-Shift-Right | Option-Shift-Right | Select word right |
Shift-Home | Shift-Home | Select line start |
Shift-End | Shift-End | Select line end |
Alt-Shift-Right | Command-Shift-Right | Select to line end |
Alt-Shift-Left | Command-Shift-Left | Select to line start |
Shift-Up | Shift-Up | Select up |
Shift-Down | Shift-Down | Select down |
Shift-PageUp | Shift-PageUp | Select page up |
Shift-PageDown | Shift-PageDown | Select page down |
Ctrl-Shift-Home | Command-Shift-Up | Select to start |
Ctrl-Shift-End | Command-Shift-Down | Select to end |
Ctrl-Shift-D | Command-Shift-D | Duplicate selection |
Ctrl-Shift-P | — | Select to matching bracket |
Multicursor
Windows/Linux | Mac | Action |
---|---|---|
Ctrl-Alt-Up | Ctrl-Option-Up | Add multi-cursor above |
Ctrl-Alt-Down | Ctrl-Option-Down | Add multi-cursor below |
Ctrl-Alt-Right | Ctrl-Option-Right | Add next occurrence to multi-selection |
Ctrl-Alt-Left | Ctrl-Option-Left | Add previous occurrence to multi-selection |
Ctrl-Alt-Shift-Up | Ctrl-Option-Shift-Up | Move multicursor from current line to the line above |
Ctrl-Alt-Shift-Down | Ctrl-Option-Shift-Down | Move multicursor from current line to the line below |
Ctrl-Alt-Shift-Right | Ctrl-Option-Shift-Right | Remove current occurrence from multi-selection and move to next |
Ctrl-Alt-Shift-Left | Ctrl-Option-Shift-Left | Remove current occurrence from multi-selection and move to previous |
Ctrl-Shift-L | Ctrl-Shift-L | Select all from multi-selection |
Go to
Windows/Linux | Mac | Action |
---|---|---|
Left | Left, Ctrl-B | Go to left |
Right | Right, Ctrl-F | Go to right |
Ctrl-Left | Option-Left | Go to word left |
Ctrl-Right | Option-Right | Go to word right |
Up | Up, Ctrl-P | Go line up |
Down | Down, Ctrl-N | Go line down |
Alt-Left, Home | Command-Left, Home, Ctrl-A | Go to line start |
Alt-Right, End | Command-Right, End, Ctrl-E | Go to line end |
PageUp | Option-PageUp | Go to page up |
PageDown | Option-PageDown, Ctrl-V | Go to page down |
Ctrl-Home | Command-Home, Command-Up | Go to start |
Ctrl-End | Command-End, Command-Down | Go to end |
Ctrl-L | Command-L | Go to line |
Ctrl-Down | Command-Down | Scroll line down |
Ctrl-Up | — | Scroll line up |
Ctrl-P | — | Go to matching bracket |
— | Option-PageDown | Scroll page down |
— | Option-PageUp | Scroll page up |
Find/Replace
Windows/Linux | Mac | Action |
---|---|---|
Ctrl-F | Command-F | Find |
Ctrl-H | Command-Option-F | Replace |
Ctrl-K | Command-G | Find next |
Ctrl-Shift-K | Command-Shift-G | Find previous |
Folding
Windows/Linux | Mac | Action |
---|---|---|
Alt-L, Ctrl-F1 | Command-Option-L, Command-F1 | Fold selection |
Alt-Shift-L, Ctrl-Shift-F1 | Command-Option-Shift-L, Command-Shift-F1 | Unfold |
Alt-0 | Command-Option-0 | Fold all |
Alt-Shift-0 | Command-Option-Shift-0 | Unfold all |