FacebookTwitterLinkedIn

English translation by ChatGPT

Ahmed Zayed 7/2/1/1 أساسيات الجافاسكريبت 'الـ Functions'Ahmed Zayed 7/2/1/1 أساسيات الجافاسكريبت 'الـ Functions'

Course

دورة تدريبية

7/2/1/1 أساسيات الجافاسكريبت 'الـ Functions'

تطوير المواقع الإلكترونية MEAN-Stack from A to Z الأساسيات Level1

عبارة عن حزمة من سطور الكود يتم كتابتها داخل مكان واحد لنتمكن من إستخدامها عدد غير محدود من المرات دون الحاجة لكتابتها في كل مرة. مثلا بفرض أنك تقوم ببرمجة موقع إلكتروني و في كل صفحة من الصفحات حينما يفتحها المستخدم تقوم بكتابة welcome و إسم المستخدم كرسالة ترحيب فهل من الأفضل كتابة الكود الذي يقوم بتلك المهمة في كل صفحة من الصفحات أم من الأفضل كتابة الكود مرة واحدة فقط و بعد ذلك يتم إستدعاءه في كل مكان نريد تنفيذ المهمة؟
هذا بإختصار تعريف الـ function أبسط أشكال الـ functions هو مجموعة من الأكود لها إسم معين يمكن إستداعها بذلك الإسم , مثل :
Code

        function SayWelcome(){
          document.write('Welcome user!!!');
      }
    
الكود السابق يحتوي علي function تسمي SayWelcome تقوم بكتابة welcome user و لكن علي حالتها تلك لن تقوم بتنفيذ أي كود , فالـ function يجب أن تتم مناداتها بإسمها حتي تقوم بتنفيذ الكود الذي تحمله و يتم منادتها عن طريق كتابة إسمها متبوعة بالأقواس () مثل
Code

         SayWelcome();
    
ايضا يمكن تمرير قيم مختلفة لإستخدامه داخل الكود في الـ function مثلا في المثال السابق المواقع ترحب بمستخدميها بأسماءهم و ليس بوصفهم مستخدمين فإذا أردنا تعديل رسالة الترحيب فإننا نقوم بتمرير إسم المستخدم عن طريق الـ function parameters مثل
Code

        function SayWelcome(userName){
          document.write('Welcome ' + userName);
      }
    
و عند منادتها يتم تمرير الإسم بهذا الشكل
Code

        SayWelcome('Ahmed');
    
الـ function من الممكن أن تأخذ أي عدد من الـ parameters و يتم الفصل بينهم بعلامة الـ comma مثل:
Code

        function SayWelcome(userName,userTime){
          document.write('Welcome ' + userName + " your time now is: " + userTime);
      }
    
و يتم إستدعاء الـ function هكذا
Code

        SayWelcome('Ahmed', new Date());
    
أيضا من الممكن أن تكون الـ function بنفسها تساوي قيمة ما بإستخدام return كما في المثال التالي:
Code

        function calc(no1,no2){
          let result = no1 + no2;
          return result;
         }
         document.write(calc(3,4));
    
في المثال السابق قمت بعمل function يتم تمرير لها رقمين و تقوم هذه الـ function بجمع الرقمين و من بعد إعادة ناتج الجمع و ذلك الناتج يمكن استخدامه مثل المتغيرات مثلا :
Code

        let i = calc(5,3);
        let x = calc(6,5) + 1;
    
مما يعني أن الـ function التي تحتوي علي return تكون مثل المتغير الذي يحتوي علي قيمة
السطر الذي يحتوي علي return هو أخر سطر يتم تنفيذه في الـ function و ما يكتب بعده يتم تجاهله لا يتم تنفيذه الـ return تعني أن كود الـ function انتهي
يمكن إعطاء قيم إفتراضية للـ parameters مثل المثال التالي:
Code

        let MyFunction =  function(name = ''){
          return 'Hi ' + name;
      }
    
بذلك عند إستدعاء الـ function و في حالة عدم تمرير متغير يتم إعتبار المتغير يساوي ‘’ (قيمة نصية فارغة.
أيضا ممكن في حالة المتغير الرقمي نعطيه قيمة إفتراضية مثل :
Code

        let MyFunction =  function(no = 0){
          return no + 1;
      }
    
و يمكن جعل الـ parameter عبارة عن array يقوم بإستقبال أي عدد من المتغيرات مثل المثال التالي:
Code

        let MyFunction =  function(...names){
          return names;
      }
      console.log(MyFunction('ahmed','omar','ali'));
    

الـ hoisting

و هو أحد الأساسيات الهامة المرتبطة بـ JS و يرتبط بالـ function في البداية ماهو الـ hoisting و ماذا يفعل ؟ من الترجمة الحرفية للكلمة و التي تعني رفع هو بالفعل يقوم بذلك, كنا قد تحدثنا من قبل عن المتغيرات و أنها ترتبط بعمليتين عملية الـ declaration و هي عملية تحديد المتغير و عملية الـ assign أو تعيين قبمة المتغير
مثل :
Code

        var x;
        //الجملة السابقة بتقوم بعملية تحديد متغير يسمي x
        x = 5;
        //أما الجملة السابقة فتقوم بتحديد قيمة المتغير
        //و يمكن أيضا دمج العملتين سويا في الجملة التالية 
        var x = 5;
    

في الطبيعي و المنطقي و في أغلب لغات البرمجة لا نستطيع أن نقوم بإستخدام متغير قبل تحديده

مثلا الكود التالي:
Code

        console.log(x);
        var x  = 5;
    
في أغلب لغات البرمجة يتسبب في خطأ error و لكن في الJS لا يتسبب في خطأ فقط سيقوم بإعطاء undefined لأن الـ JS تقوم عند التنفيذ بفصل الـ declaration عن الـ assignment فهي تري الكود بتلك الطريقة:
Code

        var x;
        console.log(x);
        x  = 5;
    
كذلك عند التعامل مع الـ functions تقوم الـ JS برفع الـ functions declaration في أول الملف فمثلا الكود التالي:
Code

        MyFunction();
        function MyFunction()
        {
            console.log('Hello!!');
        }
    
سيعمل بشكل طبيعي و لن يقوم بإحداث خطأ لأن الـ hoisting يقوم بتعديل الكود ليكون بالشكل التالي:
Code

        function MyFunction()
        {
            console.log('Hello!!');
        }
        MyFunction();
    
بالحديث عن الـ hoisting يجب علينا ان نأتي على ذكر الأنواع الاخرى من محددات المتغيرات و هم const و let حيث لا يعمل معهم الـ hoisting بنفس الطريقةو يعتقد البعض أن تلك المتغيرات لا يحدث معها الـ hoisting و لكن في الحقيقة يحدث الـ hoisting لجميع المتغيرات و الـ functions و لكن المتغيرات من نوع let و const و لكن تلك المتغيرات و لكن مع تلك الأنواع يتم تجميد المتغير فيما يعرف بالـ Temporal Dead Zone (TDZ) مما يمنع استخدامه قبل تعريفه
Code

        console.log(x);
        let x = 20;
    
الكود السابق سيتسبب في حدوث خطأ حيث لا يمكن إستخدام المتغير من نوع let قبل عمل declaration له و يمككنا إستخدام تلك الميزة مع الـ functions عن طريق الـ function expression مثل الكود التالي:
Code

        let MyFunction= function(){
          console.log('hello');
        }
        MyFunction();
    
الكود السابق يعمل بشكل جيد بينما الكود التالي سيتسبب بحدوث خطأ
Code

        MyFunction();
        let MyFunction= function(){
            console.log('hello');
        }
    
يسمي الشكل العادي للـ function بالـ function declaration مثل

      function MyFunction()
      {
          console.log('Hello!!');
      }
بينما استخدام الـ function مع let يسمي function expression أيضا يطلق علي عدة اشكال أخري من كتابة الـ functions
يجب ملاحظة أن الـ function يجب أن يتم منادتها في كل الحالات متبوعة بالأقواس (تحتوي الأقواس علي الـ parameters المراد تمريرها للـ function في حالة أحتوت الـ function علي parameters ) أما لو تم مناداتها دون الأقواس سيتم كتابة الـ function كـ text مثل :

      let MyFunction= function(){
      console.log('hello');
      }
      document.write(MyFunction);
و تكون النتيجة كتابة function(){ console.log('hello'); } في الصفحة
أيضا من المفاهيم المرتبطة بالـ function هو الـ local و الـ global عند تعريف و تعيين المتغيرات , فالمتغيرات التي يتم تعيينها داخل الـ function لا يمكن استخدامها إلا داخل الـ function بينما المتغيرات التي يتم كتابتها خارج الـ function يمكن الوصول لها و إستخدامها في أي مكان سواء من داخل function أو من خارج function حيث يمكن استخدامها globally مثل :
Code

        function MyFunction(z){
          var y =0;
          let x = 1;
      }
      
      console.log(y);
      console.log(x);
      console.log(z);
    
في الكود السايق سيحدث خطأ لمحاولة إستخدام متغيرات لم يتم عمل declaration لها حيث أنها متغيرات داخل الـ function لا يمكن أن تري في الـ global scope
يلاحظ أن الـ hoisting يحدث أيضا داخل الـ function حيث يتم رفع المتغيرات اعلى من الكود المكتوب بداخل الفانكشن
بينما في الكود التالي:
Code

        var y =10;
        let x = 11;
        let z=0;
        function MyFunction(z){
            var y =0;
            let x = 1;
        }
        console.log(y);
        console.log(x);
        console.log(z);
    
في الكود السابق لن يحدث خطأ لان هناك متغيرات بنفس الإسم في الـ global scope و هنا يجب أن بينما المتغير الـ global يمكن استخدامه من داخل الـ function مثل
Code

        var y =10;
        function MyFunction(){
        console.log(y);
        }
    
كما في المثال السابق يمكن استخدام المتغير الـ global داخل الـ function ماذا لو حاولنا تغيير قيمة المتغير الـ global من داخل الـ function بالفعل نستطيع القام بذلك و ستتغير قيمة المتغير علي المستوي الـ global
Code

        var y =10;
        function MyFunction(){
        console.log(y);
        }
    
سنحصل علي القيمة 11 في الكود السابق

الـ self invoke function

أيضا يمكن كتابة function و عمل invoke لها في نفس الوقت و هي نوع من أنواع الـ expression functions تسمي الـ self invoke function مثل الكود التالي:
Code

         (function (){
           console.log('hi JS')
          })();
    
و هي طريقة هامة تستخدم في أحيان كثيرة عندما نريد تقسيم الكود لscopes في داخل scope كبير دون الحاجة لعمل functions يعاد استخدامها مرة أخري حيث تلاحظ أن الـ function السابقة لا تملك إسم لنقوم بالمنادة عليها في مكان أخر , هي ستنفذ في مكانها مرة واحدة فقط.

الـ arrow function

من أنواع الـ expression functions و أضيفت حديثا للتسهيل حيث يمكن كتابتها كالمثال التالي:
Code

        let MyFunction = ()=>{
          return 1;
        };
        console.log(MyFunction());
    
حيث تم استبدال ()function بـ <=() ايضا يمكن الإستغناء عن الأقواس () في حالة عدم وجود parameters و استبدال الأقواس بـ _ كما في الكود التالي:
Code

        let MyFunction = _ =>{
          return 1;
      };
      console.log(MyFunction());
    
أو لو كانت تطلب متغير واحد يمكن كتابة المتغير الواحد مثل
Code

        let MyFunction =  myParam =>{
          return myParam + " hello";
      };
      console.log(MyFunction('lets say'));
    
بينما لو كان هناك أكثر من parameter سنقوم بكتابتهم بين الأقواس مثل:
Code

        let MyFunction =  (myParam,param2) =>{
          return myParam + " hello " + param2;
      };
      console.log(MyFunction('lets say', 'world'));
    
أيضا يمكن إختصار الكود و عدم كتابة الأقواس {} و عدم كتابة return في حالة أن الـ function تتكون من سطر واحد مثل الكود التالي:
Code

        let MyFunction =  (myParam) =>  myParam + ' hello world';
        console.log(MyFunction('lets say'));
    
بذلك قد تكون أكثر الجمل إختصارا لكتابة الـ arrow function كما بالمثال التالي:
Code

        let MyFunction =  _ => ' hello world';
        console.log(MyFunction());
        
    

1/1/2/7 JavaScript fundamentals 'Functions'

Web Development MEAN-Stack from A to Z Fundamentals Level1

A function is a bundle of code lines written in one place so that it can be used an unlimited number of times without needing to rewrite it each time. For example, suppose you are programming a website, and on every page, when the user opens it, you write "welcome" and the user's name as a greeting message. Is it better to write the code that performs this task on every page, or is it better to write the code once and then call it wherever you want to execute the task?
This is, in short, the definition of a function. The simplest form of a function is a set of code with a specific name that can be called by that name, like:
Code

          function SayWelcome(){
            document.write('Welcome user!!!');
        }
      
The above code contains a function called `SayWelcome` that writes "Welcome user." However, in its current state, it will not execute any code. The function must be called by its name to execute the code it contains. It is called by writing its name followed by parentheses `()`, like:
Code

           SayWelcome();
      
You can also pass different values to be used inside the function's code. For example, in the previous example, websites welcome users by their names, not as "users." If we want to modify the welcome message, we can pass the user's name through the function parameters, like:
Code

          function SayWelcome(userName){
            document.write('Welcome ' + userName);
        }
      
And when calling it, the name is passed like this:
Code

          SayWelcome('Ahmed');
      
A function can take any number of parameters, separated by commas, like:
Code

          function SayWelcome(userName,userTime){
            document.write('Welcome ' + userName + " your time now is: " + userTime);
        }
      
And the function is called like this:
Code

          SayWelcome('Ahmed', new Date());
      
A function can also return a value using `return`, as in the following example:
Code

          function calc(no1,no2){
            let result = no1 + no2;
            return result;
           }
           document.write(calc(3,4));
      
In the above example, I created a function that takes two numbers, adds them, and returns the result. This result can be used like variables, for example:
Code

          let i = calc(5,3);
          let x = calc(6,5) + 1;
      
This means that a function containing `return` is like a variable containing a value.
The line containing `return` is the last line executed in the function. Anything written after it is ignored and not executed. `return` means that the function's code has ended.
You can give default values to parameters, like in the following example:
Code

          let MyFunction =  function(name = ''){
            return 'Hi ' + name;
        }
      
Thus, when calling the function, if no variable is passed, the variable is considered equal to `''` (an empty string).
You can also give a default value to a numeric variable, like:
Code

          let MyFunction =  function(no = 0){
            return no + 1;
        }
      
You can also make the parameter an array that receives any number of variables, like in the following example:
Code

          let MyFunction =  function(...names){
            return names;
        }
        console.log(MyFunction('ahmed','omar','ali'));
      

Hoisting

Hoisting is one of the important basics related to JS and is associated with functions. First, what is hoisting, and what does it do? Literally, the word means "lifting," and indeed, it does that. We previously talked about variables and how they are associated with two processes: declaration, which is the process of defining the variable, and assignment, which is the process of assigning a value to the variable.
For example:
Code

          var x;
          // The above line defines a variable called x
          x = 5;
          // The above line assigns a value to the variable
          // You can also combine both processes in the following line
          var x = 5;
      

Normally and logically, in most programming languages, we cannot use a variable before defining it.

For example, the following code:
Code

          console.log(x);
          var x  = 5;
      
In most programming languages, this would cause an error, but in JS, it does not cause an error. Instead, it will give `undefined` because JS separates the declaration from the assignment during execution. It sees the code like this:
Code

          var x;
          console.log(x);
          x  = 5;
      
Similarly, when dealing with functions, JS lifts the function declarations to the top of the file. For example, the following code:
Code

          MyFunction();
          function MyFunction()
          {
              console.log('Hello!!');
          }
      
Will work normally and will not cause an error because hoisting modifies the code to look like this:
Code

          function MyFunction()
          {
              console.log('Hello!!');
          }
          MyFunction();
      
When talking about hoisting, we must mention the other types of variable declarations, `const` and `let`. Some people think that hoisting does not happen with these variables, but in fact, hoisting happens for all variables and functions, but for `let` and `const` variables, they are placed in a Temporal Dead Zone (TDZ), which prevents their use before they are defined.
Code

          console.log(x);
          let x = 20;
      
The above code will cause an error because a variable of type `let` cannot be used before it is declared. We can use this feature with functions through function expressions, like the following code:
Code

          let MyFunction= function(){
            console.log('hello');
          }
          MyFunction();
      
The above code works fine, while the following code will cause an error:
Code

          MyFunction();
          let MyFunction= function(){
              console.log('hello');
          }
      
The normal form of a function is called a function declaration, like:

        function MyFunction()
        {
            console.log('Hello!!');
        }
While using a function with `let` is called a function expression. There are also other forms of writing functions.
It should be noted that a function must always be called followed by parentheses (which contain the parameters to be passed to the function if the function has parameters). If it is called without parentheses, the function will be written as text. For example:

        let MyFunction= function(){
        console.log('hello');
        }
        document.write(MyFunction);
The result will be writing `function(){ console.log('hello'); }` on the page.
Another concept related to functions is local and global scope when defining and assigning variables. Variables defined inside a function cannot be used outside the function, while variables written outside the function can be accessed and used anywhere, whether inside or outside the function, as they are globally scoped. For example:
Code

          function MyFunction(z){
            var y =0;
            let x = 1;
        }
        
        console.log(y);
        console.log(x);
        console.log(z);
      
In the above code, an error will occur because it attempts to use variables that have not been declared, as they are local to the function and cannot be seen in the global scope.
Note that hoisting also happens inside functions, where variables are lifted to the top of the function's code.
While in the following code:
Code

          var y =10;
          let x = 11;
          let z=0;
          function MyFunction(z){
              var y =0;
              let x = 1;
          }
          console.log(y);
          console.log(x);
          console.log(z);
      
In the above code, no error will occur because there are variables with the same name in the global scope. Here, you must distinguish between local and global variables. While the global variable can be used inside the function, like:
Code

          var y =10;
          function MyFunction(){
          console.log(y);
          }
      
As in the above example, the global variable can be used inside the function. What if we try to change the value of the global variable from inside the function? Indeed, we can do that, and the variable's value will change globally.
Code

          var y =10;
          function MyFunction(){
          console.log(y);
          }
      
We will get the value `11` in the above code.

Self-Invoking Function

You can also write a function and invoke it at the same time. This is a type of expression function called a self-invoking function, like the following code:
Code

           (function (){
             console.log('hi JS')
            })();
      
This is an important method often used when we want to divide code into scopes within a larger scope without needing to create functions that are reused. Notice that the above function does not have a name to call it elsewhere; it will execute in its place only once.

Arrow Function

This is another type of expression function, added recently to simplify writing functions. It can be written as in the following example:
Code

          let MyFunction = () => {
            return 1;
          };
          console.log(MyFunction());
      
Here, `function()` is replaced with `() =>`. You can also omit the parentheses `()` if there are no parameters and replace them with `_`, as in the following code:
Code

          let MyFunction = _ => {
            return 1;
        };
        console.log(MyFunction());
      
Or if it requires one parameter, you can write the single parameter like:
Code

          let MyFunction =  myParam => {
            return myParam + " hello";
        };
        console.log(MyFunction('lets say'));
      
While if there are multiple parameters, they are written inside parentheses, like:
Code

          let MyFunction =  (myParam,param2) => {
            return myParam + " hello " + param2;
        };
        console.log(MyFunction('lets say', 'world'));
      
You can also shorten the code by omitting the curly braces `{}` and not writing `return` if the function consists of a single line, like the following code:
Code

          let MyFunction =  (myParam) =>  myParam + ' hello world';
          console.log(MyFunction('lets say'));
      
This can be the most concise way to write an arrow function, as in the following example:
Code

          let MyFunction =  _ => ' hello world';
          console.log(MyFunction());
          
      

February 28, 2025

Read More
إقرأ المزيد

دورة تدريبية

Course

2/1/1/1 قصة الجافاسكريبت

1/1/1/2 The Story of JavaScript

دورة تدريبية

Course

1/2/1/1 أساسيات الجافاسكريبت'المتغيرات'

1/1/2/1 JavaScript fundamentals 'Variables'

دورة تدريبية

Course

5/2/1/1 أساسيات الجافاسكريبت 'الجمل الشرطية Conditional statements'

1/1/2/5 JavaScript fundamentals 'Conditional Statements'

دورة تدريبية

Course

2/2/1/1 أساسيات الجافاسكريبت 'التعامل مع الأرقام'

1/1/2/2 JavaScript fundamentals 'Working with Numbers'

دورة تدريبية

Course

1/1/1/1 قصة المواقع الإلكترونية منذ البداية

1/1/1/1 The Story of Websites From the Beginning

Keywords
كلمات مفتاحية

دورة الـ mean-stack from a to z mean-stack دورة الـ دورة الأنجولر بالعربي دورة النود بالعربي دورة تطوير المواقع الإلكترونية

course mean-stack from a to zcourse mean-stack from a to zmean-stack courseangular arabic coursenode js arabic courseweb development course

© 2026 Ahmed Zayed. All rights reserved.© 2026 كل الحقوق محفوظة أحمد زايد