Kursinnhold
Introduction to JavaScript
Introduction to JavaScript
What Are Functions?
Functions are a feature in programming that lets us reserve a block of code to be executed later. This also enables us to execute that block of code multiple times with ease.
The basic syntax of defining a function is as follows:
js
Here function
is the keyword used to define a function, and funcName
represents the name of the function that we want to create.
Creating a function is more accurately referred to as "defining" a function. The code which defines a function is referred to as the "function definition" code.
The DRY (Don't Repeat Yourself) principle is a core programming concept that emphasizes minimizing code duplication. It encourages writing each piece of logic once and reusing it whenever necessary. This improves the code's readability and efficiency. Functions play an important role in adhering to this principle, as they allow us to eliminate any redundant code.
Following is an example of a function which draws a triangle in the console:
function drawTriangle() { console.log("*"); console.log("* *"); console.log("* * *"); console.log("* * * *"); console.log("* * * * *"); } drawTriangle();
It's possible to execute a function more than once:
function drawTriangle() { console.log("*"); console.log("* *"); console.log("* * *"); console.log("* * * *"); console.log("* * * * *"); } drawTriangle(); drawTriangle(); drawTriangle();
Executing a function is also sometimes referred to as calling a function. Similarly, a statement that executes a function (for example: myFunc()
) is referred to as a Function Call.
It is recommended to name the functions meaningfully such that the name of the function accurately reflects the operation it performs.
1. What keyword is used to define a function in JavaScript?
2. What will be the output of the following code?
3. Which of the following is NOT true about functions?
Takk for tilbakemeldingene dine!