Functions and Scope

Dear Sciaku Learner you are not logged in or not enrolled in this course.

Please Click on login or enroll now button.

If you have any query feel free to chat us!

Happy Coding! Happy Learning!

Lecture 137:- Functions and Scope

In JavaScript, functions have their own scope, which means that any variables declared inside the function are only accessible within that function's scope. This is known as function scope.

For example, consider the following code:

scssCopy code

function myFunction() {  var x = 10;  console.log(x); } myFunction(); console.log(x);

In this code, we declare a function called myFunction that sets the value of a variable x to 10 and then logs it to the console. We then call the function and also try to log the value of x outside the function.

When we run this code, we will get an error when trying to log the value of x outside the function because x only exists within the scope of the myFunction function.

It's important to note that variables declared outside of a function (i.e. global variables) are accessible from within any function in the same JavaScript file, unless they are shadowed by a variable declared within the function.

For example:

javascriptCopy code

var y = 5; function myFunction() {  var y = 10;  console.log(y); } myFunction(); console.log(y);

In this example, we declare a global variable y and then declare a local variable y inside the myFunction function. When we call the function, it logs the value of the local y variable (which is 10), and when we try to log the value of y outside the function, it logs the value of the global y variable (which is 5).

It's generally considered good practice to limit the use of global variables and to keep variables as local as possible to the functions where they are needed, in order to avoid naming collisions and other potential issues.

16. JavaScript - Functions and Array

Comments: 2

profile
@niteshguptav63
17-Nov-2024, 01:39 PM

I am not able to access videos from second class and further. I have already completed first class

profile
@niteshguptav63
16-Nov-2024, 10:56 AM

When will I get my course?

profile
@admin79
17-Nov-2024, 01:29 PM

Now, Your query was resolved.

Frequently Asked Questions (FAQs)

How do I register on Sciaku.com?
How can I enroll in a course on Sciaku.com?
Are there free courses available on Sciaku.com?
How do I purchase a paid course on Sciaku.com?
What payment methods are accepted on Sciaku.com?
How will I access the course content after purchasing a course?
How long do I have access to a purchased course on Sciaku.com?
How do I contact the admin for assistance or support?
Can I get a refund for a course I've purchased?
How does the admin grant access to a course after payment?