Assigning function to variable in JavaScript?

Use return statement to assign function to variables. Following is the code −


 Live Demo

<!DOCTYPE html>
<html lang="en">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initialscale=1.0">
<link rel="stylesheet" href="//">
<script src=""></script>
<script src=""></script>
   .demo {
      background: skyblue;
      height: 20px;
      width: 75%;
      margin: 10px;
      padding: 10px;
<div class="demo" data-st="John">John Smith</div>
<div class="demo" data-st="David">David Miller</div>
<div class="demo" data-st="Adam">Adam Smith</div>
   var studentNames = function() {
      var names = [];
      $(".demo").each(function() {
      return names.join();
   console.log( studentNames() );

To run the above program, save the file name “anyName.html(index.html)” and right click on the file. Select the option “Open with Live Server” in VS Code editor.


This will produce the following output −