Alt om Javascript


Hurtigt opslagsværk:



Syntaks:






Introduktion fra Codecademy:


Codecademy's cheatsheets

What is JavaScript? Last year, millions of learners from our community started with JavaScript. Why? JavaScript is primarily known as the language of most modern web browsers, and its early quirks gave it a bit of a bad reputation. However, the language continued to evolve and improve. JavaScript is a powerful, flexible, and fast programming language now being used for increasingly complex web development and beyond!
Since JavaScript remains at the core of web development, it's often the first language learned by self-taught coders eager to learn and build. We're excited for what you'll be able to create with the JavaScript foundation you gain here. JavaScript powers the dynamic behavior on most websites, including this one.
In this lesson, you will learn introductory coding concepts including data types and built-in objects— essential knowledge for all aspiring developers. Make sure to take notes and pace yourself. This foundation will set you up for understanding the more complex concepts you'll encounter later.




Console


The console is a panel that displays important messages, like errors, for developers. Much of the work the computer does with our code is invisible to us by default. If we want to see things appear on our screen, we can print, or log, to our console directly.
In JavaScript, the console keyword refers to an object, a collection of data and actions, that we can use in our code. Keywords are words that are built into the JavaScript language, so the computer will recognize them and treats them specially.
One action, or method, that is built into the console object is the .log() method. When we write console.log() what we put inside the parentheses will get printed, or logged, to the console.
It's going to be very useful for us to print values to the console, so we can see the work that we're doing.

This example logs 5 to the console. The semicolon denotes the end of the line, or statement. Although in JavaScript your code will usually run as intended without a semicolon, we recommend learning the habit of ending each statement with a semi-colon so you never leave one out in the few instances when they are required.
You'll see later on that we can use console.log() to print different kinds of data.



Comments


Programming is often highly collaborative. In addition, our own code can quickly become difficult to understand when we return to it— sometimes only an hour later! For these reasons, it's often useful to leave notes in our code for other developers or ourselves.
As we write JavaScript, we can write comments in our code that the computer will ignore as our program runs. These comments exist just for human reader.
Comments can explain what the code is doing, leave instructions for developers using the code, or add any other useful annotations.
There are two types of code comments in JavaScript:

  1. A single line comment will comment out a single line and is denoted with two forward slashes // preceding it.


  2. You can also use a single line comment to comment after a line of code:

  3. A multi-line comment will comment out multiple lines and is denoted with /* to begin the comment, and */ to end the comment.


  4. You can also use this syntax to comment something out in the middle of a line of code:




Data Types

Data types are the classifications we give to the different kinds of data that we use in programming. In JavaScript, there are seven fundamental data types:

  1. Number:Any number, including numbers with decimals: 4, 8, 1516, 23.42.
  2. String:Any grouping of characters on your keyboard (letters, numbers, spaces, symbols, etc.) surrounded by single quotes: ' ... ' or double quotes " ... ". Though we prefer single quotes. Some people like to think of string as a fancy word for text.
  3. Boolean:This data type only has two possible values— either true or false (without quotes). It’s helpful to think of booleans as on and off switches or as the answers to a "yes" or "no" question.
  4. Null:This data type represents the intentional absence of a value, and is represented by the keyword null (without quotes).
  5. Undefined:This data type is denoted by the keyword undefined (without quotes). It also represents the absence of a value though it has a different use than null.
  6. Symbol:A newer feature to the language, symbols are unique identifiers, useful in more complex coding. No need to worry about these for now.
  7. Object:Collections of related data.

The first 6 of those types are considered primitive data types. They are the most basic data types in the language. Objects are more complex, and you’ll learn much more about them as you progress through JavaScript. At first, seven types may not seem like that many, but soon you’ll observe the world opens with possibilities once you start leveraging each one. As you learn more about objects, you’ll be able to create complex collections of data.
But before we do that, let's get comfortable with strings and numbers!

In the example above, we first printed a string. Our string isn't just a single word; it includes both capital and lowercase letters, spaces, and punctuation.
Next, we printed the number 40, notice we did not use quotes.



Properties + concatenation!

Operators aren't just for numbers! When a + operator is used on two strings, it appends the right string to the left string:


This process of appending one string to another is called concatenation. Notice in the third example we had to make sure to include a space at the end of the first string. The computer will join the strings exactly, so we needed to make sure to include the space we wanted between the two strings.



Just like with regular math, we can combine, or chain, our operations to get a final result:



When you introduce a new piece of data into a JavaScript program, the browser saves it as an instance of the data type. Every string instance has a property called length that stores the number of characters in that string. You can retrieve property information by appending the string with a period and the property name:



The . is another operator! We call it the dot operator. In the example above, the value saved to the length property is retrieved from the instance of the string, 'Hello'. The program prints 5 to the console, because Hello has five characters in it.



Methods

Remember that methods are actions we can perform. JavaScript provides a number of string methods.
We call, or use, these methods by appending an instance with:



Let's look at each of the lines above:


You can find a list of built-in string methods in the JavaScript documentation. Developers use documentation as a reference tool. It describes JavaScript's keywords, methods, and syntax.



Built-in Objects

In addition to console, there are other objects built into JavaScript. Down the line, you’ll build your own objects, but for now these “built-in" objects are full of useful functionality.
For example, if you wanted to perform more complex mathematical operations than arithmetic, JavaScript has the built-in Math object.
The great thing about objects is that they have methods! Let's call the .random() method from the built-in Math object:



In the example above, we called the .random() method by appending the object name with the dot operator, the name of the method, and opening and closing parentheses. This method returns a random number between 0 and 1.
To generate a random number between 0 and 50, we could multiply this result by 50, like so:



The example above will likely evaluate to a decimal. To ensure the answer is a whole number, we can take advantage of another useful Math method called Math.floor().
Math.floor() takes a decimal number, and rounds down to the nearest whole number. You can use Math.floor() to round down a random number like this:



In this case:

  1. Math.random generates a random number between 0 and 1.
  2. We then multiply that number by 50, so now we have a number between 0 and 50.
  3. Then, Math.floor() rounds the number down to the nearest whole number.

To see all of the properties and methods on the Math object, take a look at the documentation here



Boolske operatorer

< mindre end 2 < 5 true
<= mindre end eller lig med 5<=5 true
== lig med 3==3 true
!= ikke lig med 3!=3 false
> større end 2>1 true
>= større end eller lig med 2>=3 false
=== lig med og samme type



Variables

In programming, a variable is a container for a value. You can think of variables as little containers for information that live in a computer's memory. Information stored in variables, such as a username, account number, or even personalized greeting can then be found in memory.

Variables also provide a way of labeling data with a descriptive name, so our programs can be understood more clearly by the reader and ourselves.

In short, variables label and store data in memory. There are only a few things you can do with variables:

  1. Create a variable with a descriptive name.
  2. Store or update information stored in a variable.
  3. Reference or "get" information stored in a variable.

It is important to distinguish that variables are not values; they contain values and represent them with a name. Observe the diagram with the colored boxes. Each box represents variables; the values are represented by the content, and the name is represented with the label.

In this lesson, we will cover how to use the var, let, and const keywords to create variables.




Create a Variable: var

There were a lot of changes introduced in the ES6 version of JavaScript in 2015. One of the biggest changes was two new keywords, let and const, to create, or declare, variables. Prior to the ES6, programmers could only use the varkeyword to declare variables.

Let's consider the example above:

  1. var, short for variable, is a JavaScript keyword that creates, or declares, a new variable.
  2. myNameis the variable's name. Capitalizing in this way is a standard convention in JavaScript called camel casing. In camel casing you group words into one, the first word is lowercase, then every word that follows will have its first letter uppercased. (e.g. camelCaseEverything).
  3. = is the assignment operator. It assigns the value ('Arya') to the variable (myName).
  4. 'Arya' is the value assigned (=) to the variable myName. You can also say that the myName variable is initialized with a value of 'Arya'.
  5. After the variable is declared, the string value 'Arya'is printed to the console by referencing the variable name: console.log(myName).

There are a few general rules for naming variables:

Note: In the next exercises, we will learn why ES6's let and constare the preferred variable keywords by many programmers. Because there is still a ton of code written prior to ES6, it's helpful to be familiar with the pre-ES6 var keyword.
If you want to learn more about varand the quirks associated with it, check out the MDN var documentation.



Create a Variable: let

As mentioned in the previous exercise, the let keyword was introduced in ES6. The let keyword signals that the variable can be reassigned a different value. Take a look at the example:

Another concept that we should be aware of when using let (and even var) is that we can declare a variable without assigning the variable a value. In such a case, the variable will be automatically initialized with a value of undefined:

Notice in the example above:



Create a Variable: const

The const keyword was also introduced in ES6, and is short for the word constant. Just like with var and let you can store any value in a const variable. The way you declare a const variable and assign a value to it follows the same structure as let and var. Take a look at the following example:

However, a const variable cannot be reassigned because it is constant. If you try to reassign a const variable, you'll get a TypeError. Constant variables must be assigned a value when declared. If you try to declare a const variable without a value, you'll get a SyntaxError. If you're trying to decide between which keyword to use, let or const, think about whether you'll need to reassign the variable later on. If you do need to reassign the variable use let, otherwise, use const.



Mathematical Assignment Operators

Let's consider how we can use variables and math operators to calculate new values and assign them to a variable. Check out the example below:

In the example above, we created the variable w with the number 4 assigned to it. The following line, w = w + 1, increases the value of w from 4 to 5.
Another way we could have reassigned w after performing some mathematical operation on it is to use built-in mathematical assignment operators. We could re-write the code above to be:

In the second example, we used the += assignment operator to reassign w. We're performing the mathematical operation of the first operator + using the number to the right, then reassigning w to the computed value.
We also have access to other mathematical assignment operators: -=, *=, and /= which work in a similar fashion.

Let's practice using these mathematical assignment operators!



The Increment and Decrement Operator

Other mathematical assignment operators include the increment operator (++) and decrement operator (--).

The increment operator will increase the value of the variable by 1. The decrement operator will decrease the value of the variable by 1. For example:

Just like the previous mathematical assignment operators (+=, -=, *=, /=), the variable's value is updated and assigned as the new value of that variable.



String Concatenation with Variables

In previous exercises, we assigned strings to variables. Now, let's go over how to connect, or concatenate, strings in variables.
The + operator can be used to combine two string values even if those values are being stored in variables:

In the example above, we assigned the value 'armadillo' to the myPet variable. On the second line, the + operator is used to combine three strings: 'I own a pet', the value saved to myPet, and '.'. We log the result of this concatenation to the console as:



String Interpolation

In the ES6 version of JavaScript, we can insert, or interpolate, variables into strings using template literals. Check out the following example where a template literal is used to log strings together:

Notice that:

One of the biggest benefits to using template literals is the readability of the code. Using template literals, you can more easily tell what the new string will be. You also don't have to worry about escaping double quotes or single quotes.




typeof operator

While writing code, it can be useful to keep track of the data types of the variables in your program. If you need to check the data type of a variable's value, you can use the typeof operator.

The typeofoperator checks the value to its right and returns, or passes back, a string of the data type.

Let's break down the first example. Since the value unknown1 is 'foo', a string, typeof unknown1 will return 'string'.




Review Variables

Nice work! This lesson introduced you to variables, a powerful concept you will use in all your future programming endeavors.

Let's review what we learned:





What are Conditional Statements?

In life, we make decisions based on circumstances. Think of an everyday decision as mundane as falling asleep— if we are tired, we go to bed, otherwise, we wake up and start our day.

These if-else decisions can be modeled in code by creating conditional statements. A conditional statement checks specific condition(s) and performs a task based on the condition(s).

In this lesson we will explore how programs make decisions by evaluating conditions and introduce logic into our code! We'll be covering the following concepts:




Eksempel på switch:







The if keyword

We often perform a task based on a condition. For example, if the weather is nice today, then we will go outside. If the alarm clock rings, then we'll shut it off. If we're tired, then we'll go to sleep.

In programming, we can also perform a task based on a condition using an if statement:


Notice in the example above, we have an if statement. The if statement is composed of:






If...Else Statements

In the previous exercise, we used an if statement that checked a condition to decide whether or not to run a block of code. In many cases, we'll have code we want to run if our condition evaluates to false. If we wanted to add some default behavior to the if statement, we can add an else statement to run a block of code when the condition evaluates to


Eksempel på if else:
var alder = 18;
var besked = alder >= 18 ? "Du er myndig" : "Du er ikke myndig";
console.log(besked); // Output: "Du er myndig"



Andet eksempel på brug af if/if else/else:

let raceNumber = Math.floor(Math.random() * 1000);
const registeredEarly = true;
const runnerAge = 18;
if (runnerAge > 18 && registeredEarly === true){
raceNumber+=1000;
}
if (runnerAge > 18 && registeredEarly === true){
console.log(`Kære løber med nummeret ${raceNumber}. Du skal løbe kl. 9.30.`);
} else if (runnerAge > 18 && registeredEarly === false) {
console.log(`Kære løber ${raceNumber}. Du skal løbe kl. 11.00`);
} else if(runnerAge == 18) {
console.log("Kære løber. Du skal gå til registreringskontoret.")
} else {
console.log(`Unge løbere, skal løbe kl. 12.30 uanset registrering eller ej. Dit løbenummer er: ${raceNumber}`);
}



Eksempel på forskellen på den gamle og nye måde at skrive if/else på:


Gammel:


Ny:







Javascript - den nyeste version - ES6

Well, despite the release of newer versions, ES6 is actually the biggest update made to ECMAScript since the first edition released in 1997! Some developers even refer to ES6 as "Modern JavaScript" because of all the major additions. There were so many great features added to help JavaScript developers that include:

Up-to-date browsers now support most of the ES6 features which allow developers to take advantage of these new additions. ES6 ultimately allows programmers to save time and write more concise code. Take for example pre-ES6 syntax for function expressions:


With ES6 arrow functions, we can transform the expression above into:


Benefits such as new ES6 syntax, make it easier to utilize a popular programming paradigm, Object Oriented Programming (OOP). With this change, developers in other languages who are used to OOP have a smoother transition into learning and using JavaScript. Another reason for the popularity of ES6 is correlated with the usage of ES6 in popular frameworks like React. So, if you want to learn the newest tools and frameworks, you will have to pick up ES6 along the way.






Funktioner

Funktioner helt basalt set:
Funktioner med parametre
Return i funktionen
Hjælpefunktioner(helper functions)
Til toppen